import { Fragment } from 'react'
import { useRecoilValue } from 'recoil'

import { isLffClient } from 'config/clients'
import { ProfileTypes } from 'config/profileTypes'

import { ProfileLink } from 'features/ProfileLink'
import { SportsFilter } from 'features/SportsFilter'
import { SelectFilter } from 'components/SelectFilter'
import { useHeaderFiltersStore } from 'features/HeaderFilters'
import { T9n } from 'features/T9n'

import {
  ScArrow,
  ScHeaderFilters,
  ScFilterItemsWrap,
  ScFilterItem,
} from './styled'

import { isSportFilterShownAtom } from '../../Atoms/HomePageAtoms'

export const HeaderFilters = () => {
  const {
    isShowTournament,
    selectedFilters,
    selectTournament,
    setIsShowTournament,
    setSelectedFilters,
    setSelectedLeague,
  } = useHeaderFiltersStore()
  const isSportFilterShown = useRecoilValue(isSportFilterShownAtom)

  const isActiveFilter = (filterItem: string) => selectedFilters.indexOf(filterItem) >= 0

  const checkFilter = (item: string) => {
    isActiveFilter(item)
      ? setSelectedFilters((prev) => prev.filter((check) => item !== check))
      : setSelectedFilters([...selectedFilters, item])
  }

  const handleClickBack = () => {
    setIsShowTournament(true)
    setSelectedFilters([])
    setSelectedLeague(['all_competitions'])
  }

  return (
    <ScHeaderFilters>
      {(!isShowTournament && selectTournament) && (
        <Fragment>
          <ScArrow
            refIcon='Arrow'
            color='#ffffff'
            direction={90}
            onClick={() => handleClickBack()}
          />
          <ProfileLink
            // страницы супертурнира не существует, возможно появится
            disabled={selectTournament.is_super_tournament}
            id={selectTournament.id}
            sportType={selectTournament.sportType}
            profileType={ProfileTypes.TOURNAMENTS}
          >
            <SelectFilter
              open={false}
              selectItem={selectTournament}
              withArrow={false}
            />
          </ProfileLink>
        </Fragment>
      )}
      {!isLffClient && isShowTournament && isSportFilterShown && <SportsFilter />}

      {isShowTournament && (
        <ScFilterItemsWrap>
          <ScFilterItem
            className={isActiveFilter('live') ? 'activeLive' : ''}
            onClick={() => checkFilter('live')}
          >
            <T9n t='live' />
          </ScFilterItem>
          <ScFilterItem
            className={isActiveFilter('upcoming') ? 'activeButton' : ''}
            onClick={() => checkFilter('upcoming')}
          >
            <T9n t='upcoming' />
          </ScFilterItem>
          <ScFilterItem
            className={isActiveFilter('completed') ? 'activeButton' : ''}
            onClick={() => checkFilter('completed')}
          >
            <T9n t='completed' />
          </ScFilterItem>
        </ScFilterItemsWrap>
      )}
    </ScHeaderFilters>
  )
}
