import {
  useState,
  useCallback,
  useEffect,
} from 'react'

import find from 'lodash/find'
import isEmpty from 'lodash/isEmpty'
import first from 'lodash/first'
import size from 'lodash/size'

import { getSubscriptions } from 'requests/getSubscriptions'
import { getSelectedSubscriptions } from 'requests/getSelectedSubscriptions'

import { useLexicsStore } from 'features/LexicsStore'

import type {
  MatchSubscriptions,
  MatchSubscription,
  MatchPackage,
  Match,
} from '../../types'
import { SubscriptionType } from '../../types'
import { transformSubscriptions } from '../helpers'
import { useSubscriptionsLexics } from './useSubscriptionsLexics'
import { checkUrlParams } from '../../../../helpers/parseUrlParams/parseUrlParams'

const defaultSubscriptions: MatchSubscriptions = []
const defaultPeriod = SubscriptionType.Month

const getInitialPeriod = (subscription?: MatchSubscription) => {
  const { packages } = subscription || {}
  if (!packages) return defaultPeriod

  return first(packages.year)?.type
  || first(packages.month)?.type
  || first(packages.pay_per_view)?.type
  || defaultPeriod
}

export const MATCH_CONFIG = {
  matchId: 2376841,
  sportId: 1,
}

export const useSubscriptions = () => {
  const { suffix } = useLexicsStore()
  const { fetchLexics } = useSubscriptionsLexics()

  const [selectedPeriod, setSelectedPeriod] = useState(defaultPeriod)
  const [
    matchSubscriptions,
    setMatchSubscriptionsList,
  ] = useState(defaultSubscriptions)
  const [
    selectedSubscription,
    setSelectedSubscription,
  ] = useState<MatchSubscription | null>(null)
  const [
    selectedPackage,
    setSelectedPackage,
  ] = useState<MatchPackage | null>(null)

  const fetchSubscriptions = useCallback(async (match: Match) => {
    let subscriptions
    if (checkUrlParams('id') && checkUrlParams('subscribe')) {
      const subs = await getSelectedSubscriptions()
      subscriptions = {
        data: subs,
        season: {
          id: 0,
          name: `${new Date().getFullYear()}`,
        },
      }
    } else {
      subscriptions = await getSubscriptions(match.sportType, match.id)
    }

    const convertedSubscriptions = transformSubscriptions({
      match,
      subscriptions,
      suffix,
    })
    setMatchSubscriptionsList(convertedSubscriptions)
    fetchLexics(subscriptions.data || [])
    const firstPackage = find(
      convertedSubscriptions, (subscription) => !isEmpty(subscription),
    )
    setSelectedPeriod(getInitialPeriod(firstPackage))
  }, [fetchLexics, suffix])

  const onSubscriptionSelect = useCallback((nextSubscription: MatchSubscription) => {
    setSelectedSubscription(nextSubscription)
    const nextPeriod = getInitialPeriod(nextSubscription)
    setSelectedPeriod(nextPeriod)
  }, [])

  const resetSubscriptions = useCallback(() => {
    setSelectedSubscription(null)
    setSelectedPackage(null)
    setMatchSubscriptionsList(defaultSubscriptions)
  }, [])

  const onPackageSelect = (subscriptionPackage: MatchPackage) => {
    setSelectedPackage(subscriptionPackage === selectedPackage ? null : subscriptionPackage)
  }

  useEffect(() => {
    if (!selectedSubscription) return

    const packages = selectedSubscription.packages[selectedPeriod]
    const isOnlySubscriptionVariant = size(packages) === 1
    if (isOnlySubscriptionVariant) {
      setSelectedPackage(packages[0])
    } else {
      setSelectedPackage(null)
    }
  }, [selectedSubscription, selectedPeriod])

  return {
    fetchSubscriptions,
    matchSubscriptions,
    onPackageSelect,
    onPeriodSelect: setSelectedPeriod,
    onSubscriptionSelect,
    resetSubscriptions,
    selectedPackage,
    selectedPeriod,
    selectedSubscription,
    setSelectedPackage,
    subscriptions: selectedSubscription?.packages?.[selectedPeriod] || [],
  }
}
