import { type FC, useState } from 'react'
import { useCreateDocument } from '../hooks/useSettingData'
import { useQueryClient } from '@tanstack/react-query'
import Button from '@/components/Button'
import Input from '@/components/Input'
import Textarea from '@/components/Textarea'
import Switch from '@/components/Switch'
import DefaulModal from '@/components/DefaulModal'

interface Props {
    open: boolean
    onClose: () => void
}

const AddDocumentModal: FC<Props> = ({ open, onClose }) => {
    const queryClient = useQueryClient()
    const createDocumentMutation = useCreateDocument()

    // Form states
    const [formData, setFormData] = useState({
        title: '',
        description: '',
        required: false
    })

    // Form errors
    const [formErrors, setFormErrors] = useState({
        title: '',
        description: ''
    })

    // Handlers
    const handleClose = () => {
        onClose()
        // Reset form when closing
        setFormData({
            title: '',
            description: '',
            required: false
        })
        setFormErrors({
            title: '',
            description: ''
        })
    }

    const handleInputChange = (field: string, value: string | boolean) => {
        setFormData(prev => ({
            ...prev,
            [field]: value
        }))
        // Clear error when user starts typing
        if (formErrors[field as keyof typeof formErrors]) {
            setFormErrors(prev => ({
                ...prev,
                [field]: ''
            }))
        }
    }

    const validateForm = () => {
        const errors = {
            title: '',
            description: ''
        }

        if (!formData.title.trim()) {
            errors.title = 'عنوان سند الزامی است'
        }

        if (!formData.description.trim()) {
            errors.description = 'توضیحات سند الزامی است'
        }

        setFormErrors(errors)
        return !errors.title && !errors.description
    }

    const handleSubmit = async () => {
        if (!validateForm()) return

        try {
            await createDocumentMutation.mutateAsync(formData)
            handleClose()
            // Refetch documents
            queryClient.invalidateQueries({ queryKey: ['documents'] })
        } catch (error) {
            console.error('Error creating document:', error)
        }
    }

    return (
        <DefaulModal
            open={open}
            close={handleClose}
            isHeader={true}
            title_header="افزودن سند جدید"
            width={500}
        >
            <div className="space-y-6 w-[400px] mt-3">
                <Input
                    label="عنوان سند"
                    value={formData.title}
                    onChange={(e) => handleInputChange('title', e.target.value)}
                    placeholder="عنوان سند را وارد کنید"
                    error_text={formErrors.title}
                />

                <Textarea
                    label="توضیحات سند"
                    value={formData.description}
                    onChange={(e) => handleInputChange('description', e.target.value)}
                    placeholder="توضیحات سند را وارد کنید"
                    error_text={formErrors.description}
                    rows={4}
                />

                <Switch
                    active={formData.required}
                    onChange={(value) => handleInputChange('required', value)}
                    label="سند ضروری است"
                />

                <div className="flex gap-3 pt-4">
                    <Button
                        label="لغو"
                        onClick={handleClose}
                        className="flex-1 bg-gray-100 text-gray-700 hover:bg-gray-200"
                    />
                    <Button
                        label={createDocumentMutation.isPending ? "در حال ذخیره..." : "ذخیره"}
                        onClick={handleSubmit}
                        disabled={createDocumentMutation.isPending}
                        className="flex-1"
                    />
                </div>
            </div>
        </DefaulModal>
    )
}

export default AddDocumentModal
