import { FC, Fragment, useState } from 'react'
import Button from '../../../components/Button'
import { useTranslation } from 'react-i18next'
import { useGetInvoiceDetail, usePayInvoice } from '../hooks/useReceiptData'
import { ErrorType } from '../../../helpers/types'
import ModalConfrim from '../../../components/ModalConfrim'
import { usePayment } from '../../wallet/hooks/useWalletData'
import { toast } from '../../../components/Toast'

type Props = {
    id: string,
    refetch: () => void,
    gateWayId: string,
}

const PayInvoice: FC<Props> = ({ id, refetch, gateWayId }) => {

    const { t } = useTranslation('global')
    const [showModal, setShowModal] = useState<boolean>(false)
    const getInvoce = useGetInvoiceDetail(id)
    const payInvoice = usePayInvoice()
    const payment = usePayment()


    const handleConfrim = () => {
        payInvoice.mutate(id, {
            onSuccess: () => {
                toast(t('success'), 'success')
                refetch()
                setShowModal(false)
            },
            onError: (error: ErrorType) => {
                toast(error.response?.data?.error.message[0], 'error')
            }
        })
    }

    const handleChartWallet = () => {
        payment.mutate({ amount: getInvoce.data?.data?.remainingToCharge, gatewayId: gateWayId, invoiceId: id }, {
            onSuccess: (data) => {
                window.location.href = data?.data?.redirectUrl
                toast(t('wallet.transfer_to_getway'), 'success')
            },
            onError: (error: ErrorType) => {
                toast(error.response?.data?.error.message[0], 'error')
            }
        })
    }

    return (
        <Fragment>
            <Button
                label={getInvoce.data?.data?.remainingToCharge > 0 ? t('receip.charge_wallet') : t('receip.pay')}
                onClick={() => setShowModal(true)}
            />

            <ModalConfrim
                title={t('receip.pay')}
                isOpen={showModal}
                close={() => setShowModal(false)}
                onConfrim={getInvoce.data?.data?.remainingToCharge > 0 ? handleChartWallet : handleConfrim}
                label={getInvoce.data?.data?.remainingToCharge > 0 ? t('receip.sure_charge_wallet') : t('receip.sure_confrim_pay')}
                isLoading={payInvoice.isPending}
            />
        </Fragment>
    )
}

export default PayInvoice