import { useEffect, useState } from 'react'

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

export const useFavouriteTeam = () => {
  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 sortTeam = (teams: Array<FavouriteTeams>) => (
    teams.sort((n1:FavouriteTeams, n2: FavouriteTeams) => {
      if (n1.name_en > n2.name_en) {
        return 1
      } if (n1.name_en < n2.name_en) {
        return -1
      }
      return 0
    }))
  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: teams1, status }: ResponseType = await getFavouriteTeam({
        country_id: 77,
        season: 30,
        sport_id: 1,
        tournament_id: 131,
      })
      const { data: teams2 }: ResponseType = await getFavouriteTeam({
        country_id: 77,
        season: 30,
        sport_id: 1,
        tournament_id: 2032,
      })
      if (!status) {
        setGroup1(sortTeam(teams1))
        setGroup2(sortTeam(teams2))
        setIsOpen(true)
      }
    })()
  }, [])

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