import {
  useState,
  useCallback,
} from 'react'

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

import { getSubscriptions } from 'requests'

import type { Match } from 'features/Matches'
import { useLexicsStore } from 'features/LexicsStore'

import type { MatchSubscriptions, MatchSubscription } from '../../types'
import { SubscriptionType } from '../../types'
import { transformSubsciptions } from '../helpers'

const defaultSubscriptions: MatchSubscriptions = {
  [SubscriptionType.Month]: [],
  [SubscriptionType.Year]: [],
  [SubscriptionType.PayPerView]: [],
}

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

  const [selectedPeriod, setSelectedPeriod] = useState(SubscriptionType.Month)
  const [matchSubscriptions, setMatchSubscriptionsList] = useState(defaultSubscriptions)
  const [selectedSubscription, setSelectedSubscription] = useState<MatchSubscription | null>(null)

  const fetchSubscriptions = useCallback((match: Match) => {
    getSubscriptions(match.sportType, match.id)
      .then((subscriptions) => transformSubsciptions({
        match,
        subscriptions,
        suffix,
      }))
      .then((subscriptions) => {
        setMatchSubscriptionsList(subscriptions)
        const firstSubscription = find(subscriptions, (subscription) => !isEmpty(subscription))
        setSelectedPeriod(first(firstSubscription)?.type || SubscriptionType.Month)
      })
  }, [suffix])

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

  const onSubscriptionSelect = (subscription: MatchSubscription) => {
    setSelectedSubscription(subscription === selectedSubscription ? null : subscription)
  }

  return {
    fetchSubscriptions,
    matchSubscriptions,
    onPeriodSelect: setSelectedPeriod,
    onSubscriptionSelect,
    resetSubscriptions,
    selectedPeriod,
    selectedSubscription,
    subscriptions: matchSubscriptions[selectedPeriod],
  }
}
