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

import filter from 'lodash/filter'

import { getSubscriptions } from 'requests'

import { SportTypes } from 'config'

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

export const useSubscriptions = () => {
  const { fetchLexics } = useLexicsFetcher()
  const [selectedPeriod, setSelectedPeriod] = useState(SubscriptionType.Month)
  const [subscriptionsList, setSubscriptionsList] = useState<MatchSubscriptions>([])
  const [selectedSubscription, setSelectedSubscription] = useState<MatchSubscription | null>(null)

  const fetchSubscriptions = useCallback((sport: SportTypes, id: number) => {
    getSubscriptions(sport, id)
      .then(transformSubsciptions)
      .then(fetchLexics)
      .then(setSubscriptionsList)
  }, [fetchLexics])

  const subscriptions = useMemo(
    () => filter(subscriptionsList, { type: selectedPeriod }),
    [selectedPeriod, subscriptionsList],
  )

  const resetSubscriptions = useCallback(() => {
    setSelectedPeriod(SubscriptionType.Month)
    setSelectedSubscription(null)
    setSubscriptionsList([])
  }, [])

  return {
    fetchSubscriptions,
    onPeriodSelect: setSelectedPeriod,
    onSubscriptionSelect: setSelectedSubscription,
    resetSubscriptions,
    selectedPeriod,
    selectedSubscription,
    subscriptions,
  }
}
