import { useState } from 'react'
import { useCurrencyConversion, useCreateOrder } from '@features/payment'

const ORDER_ERROR_MESSAGE = 'Сумма для конвертации слишком мала. Увеличьте сумму и попробуйте снова.'

type NotificationState = { status: 'error'; message: string }

export function useConverterSection() {
  const conv = useCurrencyConversion()
  const [agreed, setAgreed] = useState(false)
  const [notification, setNotification] = useState<NotificationState | null>(null)
  const { mutate: submitOrder, isPending } = useCreateOrder()

  function onPay() {
    setNotification(null)
    submitOrder(
      conv.isUsdtToRub
        ? { usdt_amount: conv.numUsdt, usdt_exchange_rate: 1, gas_fee: 1, total_price: conv.rubTotalNum }
        : { usdt_amount: conv.usdtFromRubNum, usdt_exchange_rate: 1, gas_fee: 1, total_price: conv.numRubInput },
      {
        onError: () => setNotification({ status: 'error', message: ORDER_ERROR_MESSAGE }),
      },
    )
  }

  const isPayDisabled = conv.isUsdtToRub
    ? (!conv.rubTotal || isPending || !agreed)
    : (!conv.usdtFromRub || isPending || !agreed || conv.rubBelowMin)

  return {
    ...conv,
    agreed,
    setAgreed,
    onPay,
    isPending,
    isPayDisabled,
    notification,
    dismissNotification: () => setNotification(null),
  }
}
