import { type FC, useEffect, useState } from 'react'
import DefaulModal from '@/components/DefaulModal'
import DatePicker from '@/components/DatePicker'
import Textarea from '@/components/Textarea'
import UploadBox from '@/components/UploadBox'
import Button from '@/components/Button'
import { useCompleteCancel } from '@/pages/orders/hooks/useOrderData'
import { useUploadSingle } from '@/pages/uploader/hooks/useUploaderData'
import { useQueryClient } from '@tanstack/react-query'
import { toast } from 'react-toastify'
import { extractErrorMessage } from '@/helpers/utils'

type Props = {
    open: boolean
    onClose: () => void
    cancelId: string
    onSuccess?: () => void
}

const CompleteCancelModal: FC<Props> = ({ open, onClose, cancelId, onSuccess }) => {
    const [refundDate, setRefundDate] = useState('')
    const [refundComment, setRefundComment] = useState('')
    const [refundReceiptFile, setRefundReceiptFile] = useState<File[]>([])
    const [isUploading, setIsUploading] = useState(false)

    const completeCancel = useCompleteCancel()
    const uploadSingle = useUploadSingle()
    const queryClient = useQueryClient()

    const resetForm = () => {
        setRefundDate('')
        setRefundComment('')
        setRefundReceiptFile([])
        setIsUploading(false)
    }

    useEffect(() => {
        if (!open) {
            resetForm()
        }
    }, [open])

    const handleClose = () => {
        resetForm()
        onClose()
    }

    const handleSubmit = async () => {
        if (!cancelId) {
            toast.error('شناسه کنسلی نامعتبر است')
            return
        }

        try {
            setIsUploading(true)
            let receiptUrl = ''

            if (refundReceiptFile.length > 0) {
                const uploadResponse = await uploadSingle.mutateAsync(refundReceiptFile[0])
                receiptUrl = uploadResponse?.results?.url?.url || ''
            }

            await completeCancel.mutateAsync({
                id: cancelId,
                params: {
                    refundDate,
                    refundComment,
                    refundReceipt: receiptUrl,
                },
            })

            await queryClient.invalidateQueries({ queryKey: ['cancels'] })
            toast.success('کنسلی با موفقیت تکمیل شد')
            handleClose()
            onSuccess?.()
        } catch (error) {
            toast.error(extractErrorMessage(error))
        } finally {
            setIsUploading(false)
        }
    }

    return (
        <DefaulModal
            open={open}
            close={handleClose}
            isHeader
            title_header='تکمیل کنسلی'
        >
            <div className='space-y-4 mt-4 w-full sm:w-[420px]'>
                <div>
                    <DatePicker
                        label='تاریخ بازگشت وجه'
                        placeholder='تاریخ را انتخاب کنید'
                        onChange={(date) => setRefundDate(date)}
                        defaulValue={refundDate}
                    />
                </div>

                <Textarea
                    label='توضیحات بازگشت وجه'
                    placeholder='توضیحات را وارد کنید'
                    value={refundComment}
                    onChange={(event) => setRefundComment(event.target.value)}
                    rows={4}
                />

                <UploadBox
                    label='رسید بازگشت وجه'
                    onChange={(files) => setRefundReceiptFile(files)}
                    isReset={!open}
                />

                <div className='flex justify-end items-center pt-4'>
                    <div className='flex gap-3'>
                        <Button
                            onClick={handleClose}
                            className='bg-gray-200 hover:bg-gray-300 text-gray-700 w-fit'
                        >
                            انصراف
                        </Button>
                        <Button
                            onClick={handleSubmit}
                            className='bg-blue-600 hover:bg-blue-700 text-white w-fit'
                            disabled={!refundDate || !refundComment || isUploading || completeCancel.isPending}
                        >
                            {isUploading || completeCancel.isPending ? 'در حال انجام...' : 'تکمیل کنسلی'}
                        </Button>
                    </div>
                </div>
            </div>
        </DefaulModal>
    )
}

export default CompleteCancelModal

