import { useState, type FC } from 'react'
import Button from '../../../components/Button'
import DefaulModal from '../../../components/DefaulModal'
import { usePayment } from '../hooks/useResellerData'
import Input from '../../../components/Input'
import { toast } from '../../../components/Toast';
import { ErrorType } from '../../../helpers/types'

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

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

    const payment = usePayment()
    const [showModal, setShowModal] = useState<boolean>(false)
    const [transactionId, setTransactionId] = useState<string>('')

    const handleSubmit = () => {
        if (transactionId.length > 0) {
            payment.mutate({ id: id, transactionId: transactionId }, {
                onSuccess: () => {
                    toast('با موفقت ثبت شد')
                    setTransactionId('')
                    refetch()
                },
                onError: (error: ErrorType) => {
                    toast(error.response?.data?.error.message[0], 'error')
                }
            })
        } else {
            toast('شماره تراکنش رو پر کنید', 'error')
        }
    }

    return (
        <div>
            <Button
                className='w-fit px-4'
                label='پرداخت'
                onClick={() => setShowModal(true)}
            />

            <DefaulModal
                open={showModal}
                close={() => setShowModal(false)}
                isHeader
                title_header='پرداخت'
            >
                <div className='mt-4'>
                    <Input
                        value={transactionId}
                        onChange={(e) => setTransactionId(e.target.value)}
                        label='شماره تراکنش'
                    />
                </div>

                <div className='mt-5'>
                    <Button
                        label='ثبت'
                        onClick={handleSubmit}
                        isLoading={payment.isPending}
                    />
                </div>

            </DefaulModal>
        </div>
    )
}

export default Payment