import React, { useState, useEffect } from 'react'
import { type FC } from 'react'
import Button from '../../../components/Button'
import Input from '../../../components/Input'
import DefaulModal from '../../../components/DefaulModal'
import { useUpdateBanner } from '../hooks/useSettingData'
import { useUploadSingle } from '../../../pages/uploader/hooks/useUploaderData'
import { type BannerItem, type UpdateBannerType } from '../types/Types'
import { toast } from 'react-toastify'
import { extractErrorMessage } from '@/helpers/utils'
import UploadBox from '../../../components/UploadBox'
import Switch from '../../../components/Switch'

interface EditBannerModalProps {
    banner: BannerItem
    isOpen: boolean
    onClose: () => void
    onSuccess: () => void
}

const EditBannerModal: FC<EditBannerModalProps> = ({ banner, isOpen, onClose, onSuccess }) => {
    const [formData, setFormData] = useState<UpdateBannerType>({
        imageUrl: '',
        altText: '',
        title: '',
        linkUrl: '',
        isActive: true,
        order: 1,
    })

    const [imageFile, setImageFile] = useState<File[]>([])

    const updateBannerMutation = useUpdateBanner()
    const uploadSingle = useUploadSingle()

    useEffect(() => {
        if (banner) {
            setFormData({
                imageUrl: banner.imageUrl,
                altText: banner.altText,
                title: banner.title,
                linkUrl: banner.linkUrl,
                isActive: banner.isActive,
                order: banner.order,
            })
        }
    }, [banner])

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault()

        if (!formData.title || !formData.altText || !formData.linkUrl) {
            toast.error('لطفا تمام فیلدهای الزامی را پر کنید')
            return
        }

        if (!formData.order || formData.order < 1) {
            toast.error('ترتیب نمایش باید یک عدد مثبت باشد')
            return
        }

        try {
            let finalImageUrl = formData.imageUrl

            // Upload new image if selected
            if (imageFile.length > 0) {
                const uploadResponse = await uploadSingle.mutateAsync(imageFile[0])
                finalImageUrl = uploadResponse.results?.url?.url

                if (!finalImageUrl) {
                    toast.error('خطا در آپلود تصویر')
                    return
                }
            }

            // Update banner
            await updateBannerMutation.mutateAsync({
                id: banner._id,
                params: {
                    imageUrl: finalImageUrl,
                    altText: formData.altText,
                    title: formData.title,
                    linkUrl: formData.linkUrl,
                    isActive: formData.isActive,
                    order: formData.order,
                }
            }, {
                onError: (error) => {
                    toast.error(extractErrorMessage(error))
                }
            })

            toast.success('بنر با موفقیت بروزرسانی شد')
            handleClose()
            onSuccess()
        } catch (error) {
            toast.error('خطا در آپلود تصویر')
        }
    }

    const handleClose = () => {
        setFormData({
            imageUrl: '',
            altText: '',
            title: '',
            linkUrl: '',
            isActive: true,
            order: 1,
        })
        setImageFile([])
        onClose()
    }

    return (
        <DefaulModal open={isOpen} close={handleClose} isHeader={true} title_header="ویرایش بنر">
            <form onSubmit={handleSubmit} className="w-[500px] mt-4 space-y-6">
                {/* تصویر بنر */}
                <div>
                    <div className="mb-4">
                        <img
                            src={formData.imageUrl}
                            alt={formData.altText}
                            className="w-full h-32 object-cover rounded border"
                            onError={(e) => {
                                const target = e.target as HTMLImageElement
                                target.src = '/placeholder-image.png'
                            }}
                        />
                    </div>
                    <UploadBox
                        label='تصویر جدید بنر (اختیاری)'
                        isMultiple={false}
                        onChange={(files) => setImageFile(files)}
                    />
                </div>

                {/* عنوان */}
                <div>
                    <Input
                        label='عنوان بنر'
                        value={formData.title}
                        onChange={(e) => setFormData(prev => ({ ...prev, title: e.target.value }))}
                        placeholder="عنوان بنر را وارد کنید"
                        required
                    />
                </div>

                {/* متن جایگزین */}
                <div>
                    <Input
                        label='متن جایگزین (Alt Text)'
                        value={formData.altText}
                        onChange={(e) => setFormData(prev => ({ ...prev, altText: e.target.value }))}
                        placeholder="توضیح تصویر برای دسترسی"
                        required
                    />
                </div>

                {/* لینک */}
                <div>
                    <Input
                        label='لینک مقصد'
                        value={formData.linkUrl}
                        onChange={(e) => setFormData(prev => ({ ...prev, linkUrl: e.target.value }))}
                        placeholder="https://example.com"
                        required
                    />
                </div>

                {/* ترتیب نمایش */}
                <div>
                    <Input
                        label='ترتیب نمایش'
                        type='number'
                        value={formData.order}
                        onChange={(e) => setFormData(prev => ({ ...prev, order: parseInt(e.target.value) || 1 }))}
                        placeholder="1"
                        min={1}
                        required
                    />
                </div>

                {/* وضعیت */}
                <div>
                    <Switch
                        active={formData.isActive}
                        onChange={(value) => setFormData(prev => ({ ...prev, isActive: value }))}
                        label="فعال"
                    />
                </div>

                <div className="flex gap-3 pt-4">
                    <Button
                        type="submit"
                        variant="primary"
                        className="flex-1"
                        disabled={updateBannerMutation.isPending || uploadSingle.isPending}
                        isLoading={updateBannerMutation.isPending || uploadSingle.isPending}
                    >
                        {(updateBannerMutation.isPending || uploadSingle.isPending) ? 'در حال بروزرسانی...' : 'بروزرسانی'}
                    </Button>
                    <Button
                        type="button"
                        variant="outline"
                        className="flex-1"
                        onClick={handleClose}
                        disabled={updateBannerMutation.isPending || uploadSingle.isPending}
                    >
                        لغو
                    </Button>
                </div>
            </form>
        </DefaulModal>
    )
}

export default EditBannerModal
