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

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

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

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


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

    return (
        <Fragment>
            <Button
                label={t('receip.pay')}
                onClick={() => setShowModal(true)}
            />

            <ModalConfrim
                isOpen={showModal}
                close={() => setShowModal(false)}
                onConfrim={handleConfrim}
                label={t('receip.sure_confrim_pay')}
                isLoading={payInvoice.isPending}
            />
        </Fragment>
    )
}

export default PayInvoice