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

import last from 'lodash/last'

import type { Match } from 'features/Matches/hooks'
import { Steps } from 'features/BuyMatchPopup/types'

import { useSubscriptions } from './useSubscriptions'

type MatchData = Pick<Match, (
  'id'
  | 'team1'
  | 'team2'
  | 'sportType'
)> | null

export const useBuyMatchPopup = () => {
  const [steps, setSteps] = useState<Array<Steps>>([])
  const [match, setMatch] = useState<MatchData>(null)

  const goTo = useCallback(
    (step: Steps, e?: MouseEvent<HTMLButtonElement>) => setSteps((state) => {
      e?.stopPropagation()
      return [...state, step]
    }),
    [],
  )
  const goBack = useCallback(() => setSteps((state) => {
    const newState = [...state]
    newState.pop()
    return newState
  }), [])

  const openPopup = (matchData: MatchData) => {
    setMatch(matchData)
    setSteps([Steps.Subscriptions])
  }

  const {
    fetchSubscriptions,
    onPeriodSelect,
    onSubscriptionSelect,
    resetSubscriptions,
    selectedPeriod,
    selectedSubscription,
    subscribeToMatches,
    subscriptions,
  } = useSubscriptions(goTo)

  const closePopup = () => {
    setMatch(null)
    setSteps([])
    resetSubscriptions()
  }

  useEffect(() => {
    if (match) {
      fetchSubscriptions(match.sportType, match.id)
    }
  }, [match, fetchSubscriptions])

  return {
    close: closePopup,
    currentStep: last(steps),
    goBack,
    goTo,
    match,
    onPeriodSelect,
    onSubscriptionSelect,
    open: openPopup,
    selectedPeriod,
    selectedSubscription,
    subscribeToMatches,
    subscriptions,
  }
}
