import { atom, selector } from 'recoil'

import type { Match } from 'requests'

export type MatchType = Match & {
  isChecked: boolean,
}

export type PlayerMatchesType = Array<MatchType>

type DataForm = {
  data: {
    background_music: string | null,
    duration: number,
    lang: string,
    matches: Array<number>,
    player_id: number,
    price: number,
    sport_id: number,
    stats: boolean,
  },
  isDisabledButton: boolean,
  isOpenThanksPopup: boolean,
}

export const playerMatchesState = atom({
  default: [] as PlayerMatchesType,
  key: 'playerMatchesState',
})

export const openPopupChangeCard = atom({
  default: false,
  key: 'openPopupChangeCard',
})

export const dataForPayHighlights = atom({
  default: {} as DataForm,
  key: 'dataForPayHighlights',
})

export const fetchingMatches = atom({
  default: false,
  key: 'fetchingMatches',
})

export const checkedMatches = selector({
  get: ({ get }) => {
    const matches = get(playerMatchesState)
    const checkedPlayerMatches = matches?.filter(({ isChecked }) => isChecked)
    const idsCheckedMatches = checkedPlayerMatches?.map(({ id }) => id)
    const checkedMatchesLength = checkedPlayerMatches?.length

    return {
      checkedMatchesLength,
      checkedPlayerMatches,
      idsCheckedMatches,
    }
  },
  key: 'checkedMatches',
})
