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

import find from 'lodash/find'

import type { Cards } from 'requests/getCardsList'
import { getCardsList } from 'requests/getCardsList'
import { addCard } from 'requests/addCard'
import { deleteCard } from 'requests/deleteCard'
import { setDefaultCard as setDefaultCardRequest } from 'requests/setDefaultCard'

import { useRequest, useToggle } from 'hooks'
import { PAGES } from 'config'

export const useBankCards = () => {
  const {
    isOpen: infoModalOpen,
    toggle: toggleInfoModal,
  } = useToggle()

  const [isHighlightsPage, setIsHighlightsPage] = useState(false)
  const [error, setError] = useState('')
  const [cards, setCards] = useState<Cards | null>(null)
  const [lastCard, setLastCard] = useState<string | null>(null)
  const defaultCard = useMemo(
    () => find(cards, { default: true }),
    [cards],
  )

  const fetchCards = useCallback(() => getCardsList().then(setCards), [])

  const onAddCard = async (token: string) => (
    addCard(token)
      .catch(() => {
        setError('error_can_not_add_card')
        return Promise.reject()
      })
      .then(({ card }) => {
        isHighlightsPage && setLastCard(card.id)
      })
      .then(fetchCards)
  )

  const onDeleteCard = (cardId: string) => deleteCard(cardId).then(fetchCards)
  const { isFetching, request: handleCardDelete } = useRequest(onDeleteCard)

  const onSetDefaultCard = (cardId: string) => {
    setDefaultCardRequest(cardId).then(fetchCards)
  }

  useEffect(() => {
    setIsHighlightsPage(window.location.pathname === PAGES.highlights)

    return () => {
      setError('')
      setLastCard(null)
      setIsHighlightsPage(false)
    }
  }, [cards])

  return {
    cards,
    defaultCard,
    error,
    fetchCards,
    infoModalOpen,
    isFetching,
    isHighlightsPage,
    lastCard,
    onAddCard,
    onDeleteCard: handleCardDelete,
    onSetDefaultCard,
    setError,
    setLastCard,
    toggleInfoModal,
  }
}
