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

interface CreateSliderModalProps {
    isOpen: boolean
    onClose: () => void
    onSuccess: () => void
}

const CreateSliderModal: FC<CreateSliderModalProps> = ({ isOpen, onClose }) => {
    const [formData, setFormData] = useState<CreateSliderType>({
        displayLocation: 'desktop',
        imageUrl: '',
        altText: '',
        title: '',
        linkUrl: '',
        isActive: true,
    })

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

    const createSliderMutation = useCreateSlider()
    const uploadSingle = useUploadSingle()

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

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

        if (imageFile.length === 0) {
            toast.error('لطفا تصویر اسلایدر را انتخاب کنید')
            return
        }

        try {
            // Upload image first
            const uploadResponse = await uploadSingle.mutateAsync(imageFile[0])
            const imageUrl = uploadResponse.results?.url?.url

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

            // Create slider with uploaded image URL
            await createSliderMutation.mutateAsync({
                displayLocation: formData.displayLocation,
                imageUrl,
                altText: formData.altText,
                title: formData.title,
                linkUrl: formData.linkUrl,
                isActive: formData.isActive,
            }, {
                onError: (error) => {
                    toast.error(extractErrorMessage(error))
                }
            })

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

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

    const displayLocationOptions = [
        { value: 'desktop', label: 'دسکتاپ' },
        { value: 'mobile', label: 'موبایل' },
    ]

    return (
        <DefaulModal open={isOpen} close={handleClose} isHeader={true} title_header="افزودن اسلایدر جدید">
            <form onSubmit={handleSubmit} className="w-[500px] mt-4 space-y-6">
                {/* محل نمایش */}
                <div>
                    <Select
                        label='محل نمایش'
                        value={formData.displayLocation}
                        onChange={(e) => setFormData(prev => ({ ...prev, displayLocation: e.target.value as 'desktop' | 'mobile' }))}
                        items={displayLocationOptions}
                        required
                    />
                </div>

                {/* تصویر اسلایدر */}
                <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="/summer-sale"
                        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={createSliderMutation.isPending || uploadSingle.isPending}
                        isLoading={createSliderMutation.isPending || uploadSingle.isPending}
                    >
                        {(createSliderMutation.isPending || uploadSingle.isPending) ? 'در حال ذخیره...' : 'ذخیره'}
                    </Button>
                    <Button
                        type="button"
                        variant="outline"
                        className="flex-1"
                        onClick={handleClose}
                        disabled={createSliderMutation.isPending || uploadSingle.isPending}
                    >
                        لغو
                    </Button>
                </div>
            </form>
        </DefaulModal>
    )
}

export default CreateSliderModal

