import { useEffect, useState } from 'react'

import {
  getUserSubscribes,
  Subscribe,
  Subscribes,
} from 'requests/getUserSubscribes'
import { cancelSubscribe } from 'requests/cancelSubscribe'

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

export const useUserSubscribes = () => {
  const { addLexicsConfig } = useLexicsStore()

  const [selectedSubscribe, setSelectedSubscribe] = useState<Subscribe>({} as Subscribe)
  const [subscribes, setSubscribes] = useState<Subscribes>([])
  const [isCancelPopupOpen, setIsCancelPopupOpen] = useState(false)
  const [changeCardPopupOpen, setChangeCardPopupOpen] = useState(false)
  const [isSubCanceled, setSubCanceled] = useState(false)
  const [isFetching, setIsFetching] = useState(false)
  const [error, setError] = useState('')
  const { user } = useAuthStore()

  const handleClose = () => {
    setIsCancelPopupOpen(false)
    setChangeCardPopupOpen(false)
    setError('')
  }

  const cancelSub = async () => {
    try {
      setIsFetching(true)
      if (selectedSubscribe?.sub_id) {
        await cancelSubscribe(selectedSubscribe?.sub_id)
        setSubCanceled(true)
      }
    } catch {
      setError('error_payment_unsuccessful')
    }
    setIsFetching(false)
  }

  useEffect(() => {
    (async () => {
      setIsFetching(true)
      const allSubscribes = (await (getUserSubscribes(user?.profile?.email || '')))
        .sort((a, b) => Date.parse(b.access_to) - Date.parse(a.access_to))
      setSubscribes(allSubscribes)
      addLexicsConfig(allSubscribes.map(({ lexic }) => lexic))
      setIsFetching(false)
    })()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  return {
    cancelSub,
    changeCardPopupOpen,
    error,
    handleClose,
    isCancelPopupOpen,
    isFetching,
    isSubCanceled,
    selectedSubscribe,
    setChangeCardPopupOpen,
    setIsCancelPopupOpen,
    setSelectedSubscribe,
    subscribes,
  }
}
