import { useEffect, useState } from 'react'

import {
  getFavouriteTeam,
  FavouriteTeams,
  ResponseType,
} from 'requests/getFavouriteTeam'
import { saveFavouriteTeam } from 'requests/saveFavouriteTeam'

/* eslint-disable */
const groupTeams = {
  1086: 'group_1',
  7032: 'group_1',
  6132: 'group_1',
  7321: 'group_1',
  62: 'group_1',
  7329: 'group_1',
  17958: 'group_1',
  1076: 'group_1',
  6337: 'group_1',
  9114: 'group_1',
  9143: 'group_1',
  7011: 'group_1',
  6996: 'group_1',
  3945: 'group_1',
  6330: 'group_1',
  7346: 'group_1',
  6331: 'group_1',
  31608: 'group_1',
  6335: 'group_1',
  6332: 'group_1',
  9108: 'group_1',
  1089: 'group_2',
  7102: 'group_2',
  7018: 'group_2',
  6549: 'group_2',
  3965: 'group_2',
  2103: 'group_2',
  167340: 'group_2',
  6606: 'group_2',
  7016: 'group_2',
  7015: 'group_2',
  7288: 'group_2',
  1093: 'group_2',
  1092: 'group_2',
  1085: 'group_2',
  3882: 'group_2',
  7307: 'group_2',
  7306: 'group_2',
  7108: 'group_2',
  1088: 'group_2',
  1077: 'group_2',
}

export const useFavouriteTeam = () => {
  const [teams, setTeams] = useState<Array<FavouriteTeams>>([])
  const [activeId, setActiveId] = useState<number | null>(null)
  const [isOpen, setIsOpen] = useState<boolean>(false)
  const [group1, setGroup1] = useState<Array<FavouriteTeams>>([])
  const [group2, setGroup2] = useState<Array<FavouriteTeams>>([])

  const changeActive = (team: FavouriteTeams) => {
    setActiveId((prev) => (prev === team.id ? null : team.id))
  }

  const onSaveFavouriteTeam = () => {
    activeId && saveFavouriteTeam(
        {
          answer_id: activeId,
          survey_id: 1,
        })
    setIsOpen(false)
  }


  useEffect(  () => {
    (async () => {
      const { data, status }: ResponseType = await getFavouriteTeam({
        country_id: 77,
        season: 30,
        sport_id: 1,
        tournament_id: 131,
      })
      if(!status) {
        setTeams(data.sort((n1:FavouriteTeams , n2: FavouriteTeams) => {
          if (n1.name_en > n2.name_en) {
            return 1;
          } else if (n1.name_en < n2.name_en) {
            return -1;
          }
          return 0;
        }))
        setIsOpen(true)
      }else{
        return
      }
    })()
  }, [])

  useEffect(() => {
    setGroup1(teams?.filter(
      (team: FavouriteTeams) => groupTeams[team.id as keyof typeof groupTeams] === 'group_1',
    ))
    setGroup2(teams?.filter(
      (team: FavouriteTeams) => groupTeams[team.id as keyof typeof groupTeams] === 'group_2',
    ))
  }, [teams])

  return {
    activeId,
    changeActive,
    group1,
    group2,
    isOpen,
    onSaveFavouriteTeam,
  }
}
