import {
  useEffect,
  useState,
} from 'react'

import size from 'lodash/size'
import includes from 'lodash/includes'

import { PAGES } from 'config'

import type { TournamentInfo } from 'requests/getTournamentInfo'
import type { Landing } from 'requests/getLanding'
import { getLanding } from 'requests/getLanding'
import { getLandingLogo } from 'requests/getLandingMedia'
import { getTournamentInfo } from 'requests/getTournamentInfo'

import { redirectToUrl } from 'helpers/redirectToUrl'

import { useLexicsStore } from 'features/LexicsStore'
import { useAuthStore } from 'features/AuthStore'

import { getLandingName, isPastLandingDate } from './helpers'
import { getName, useName } from '../Name'

export const useLandings = () => {
  const [tournamentInfo, setTournamentInfo] = useState<Landing | null>(null)
  const [isInactiveLanding, setIsInactiveLanding] = useState(false)
  const [isNonExistLanding, setIsNonExistLanding] = useState(false)
  const [nonExistLogoSrc, setNonExistLogoSrc] = useState('')
  const [tournamentProfile, setTournamentProfile] = useState<TournamentInfo>(null)

  const { addLexicsConfig, suffix } = useLexicsStore()
  const {
    landingUrlFrom,
    setIsFromLanding,
    user,
  } = useAuthStore()

  const buttonLexic = tournamentInfo?.lexic_button || ''
  const period = tournamentInfo?.lexic_period || ''
  const title = tournamentInfo?.lexic_title || ''
  const description = tournamentInfo?.lexic_description || ''
  const gallery = tournamentInfo?.media.gallery

  useEffect(() => {
    const lexics = [buttonLexic, period, title, description]
    addLexicsConfig(lexics)
  }, [
    addLexicsConfig,
    buttonLexic,
    description,
    period,
    title,
  ])

  const redirectToHomePage = () => redirectToUrl(PAGES.home)
  const onButtonClick = () => {
    if (includes(landingUrlFrom, PAGES.match) || includes(landingUrlFrom, PAGES.tournament)) {
      setIsFromLanding(true)
      redirectToUrl(landingUrlFrom)
      sessionStorage.removeItem('landingUrlFrom')
    } else {
      redirectToUrl(tournamentInfo?.url_button || '')
    }
  }

  useEffect(() => {
    (async () => {
      const landingData = sessionStorage.getItem('landingData')
      const parseLandingData = landingData && JSON.parse(landingData)

      if (parseLandingData && parseLandingData.defaultLanding) {
        getTournamentInfo(parseLandingData.sportType, parseLandingData.tournamentId)
          .then(setTournamentProfile)
        setIsNonExistLanding(true)
        return getLandingLogo({
          sport_id: parseLandingData.sportType,
          tournament_id: parseLandingData.tournamentId,
        })
          .then(({ logo_url }) => setNonExistLogoSrc(logo_url || '/images/tournament-fallback.png'))
      }

      try {
        const data = landingUrlFrom
          ? await getLanding({
            landingName: parseLandingData.landing_id || parseLandingData.url_landing,
            seasonId: parseLandingData.season_id,
            sportId: parseLandingData.sport_id,
            tournamentId: parseLandingData.tournament_id,
          })
          : await getLanding({ landingName: getLandingName() })

        if (user) return redirectToUrl(data.url_button || '')

        if (isPastLandingDate(data.date_to)) setIsInactiveLanding(true)

        return setTournamentInfo(data)
      } catch (err) {
        return redirectToHomePage()
      }
    })()
  }, [landingUrlFrom, user])

  const [sliderItemId, setSliderItemId] = useState(0)

  const onSliderSwitchClick = (itemId: number) => setSliderItemId(itemId)

  const imgCounter = size(gallery)

  useEffect(() => {
    if (sliderItemId === imgCounter) {
      setSliderItemId(0)
    }
    const getSliderInterval = setInterval(() => {
      setSliderItemId(sliderItemId + 1)
    }, 5000)
    return () => clearInterval(getSliderInterval)
  }, [imgCounter, sliderItemId])

  const inActiveLandingData = () => {
    if (!tournamentInfo?.tournaments || !isInactiveLanding) return null

    const {
      season,
      tournament_eng,
      tournament_rus,
    } = tournamentInfo.tournaments[0]

    const currentTournamentsTitle = {
      name_eng: tournament_eng,
      name_rus: tournament_rus,
    }

    const tournamentsTitle = getName({ nameObj: currentTournamentsTitle, suffix })

    return {
      season,
      tournamentsTitle,
    }
  }

  const defaultTournamentName = useName(tournamentProfile || {})

  return {
    buttonColor: tournamentInfo?.button_color,
    buttonLexic,
    defaultTournamentName,
    description,
    gallery,
    inActiveLandingData,
    isInactiveLanding,
    isNonExistLanding,
    logo: tournamentInfo?.media.logo,
    logoInsports: tournamentInfo?.logo_insports,
    nonExistLogoSrc,
    onButtonClick,
    onSliderSwitchClick,
    period,
    redirectToHomePage,
    sliderItemId,
    teams: tournamentInfo?.teams,
    title,
    tournamentInfo,
  }
}
