import {
  useCallback,
  useState,
  useMemo,
} 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'

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

  const [error, setError] = useState('')
  const [cards, setCards] = useState<Cards | 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(fetchCards)
  )

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

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

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