import { useState, useEffect } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { ArrowRight, FolderOpen } from 'lucide-react';
import { Button } from '../../../components/ui/Button';
import { Input } from '../../../components/ui/Input';
import { FileUploader } from '../../../components/ui/FileUploader';
import { useFileUpload, useFileDelete } from '../../../hooks/useFileUpload';
import { useToast } from '../../../contexts/ToastContext';
import { useCategory, useCreateCategory, useUpdateCategory } from '../core/_hooks';
import { FormHeader, PageContainer, Label } from '../../../components/ui/Typography';

const CategoryFormPage = () => {
    const navigate = useNavigate();
    const { id } = useParams();
    const { success: showToast } = useToast();
    const isEdit = Boolean(id);

    const [formData, setFormData] = useState({
        name: '',
        description: '',
        parent_id: null as number | null,
        file_id: undefined as number | undefined,
    });

    const [uploadedImage, setUploadedImage] = useState<{ id: string, url: string } | null>(null);
    const [isUploading, setIsUploading] = useState(false);

    const { data: category, isLoading: isLoadingCategory } = useCategory(
        id || '0',
        isEdit
    );

    const createMutation = useCreateCategory();
    const updateMutation = useUpdateCategory();
    const { mutateAsync: uploadFile } = useFileUpload();
    const { mutate: deleteFile } = useFileDelete();

    useEffect(() => {
        if (category && isEdit) {
            const fileId = (category as any).file?.id ?? category.file_id;
            const fileUrl = (category as any).file?.url || '';

            setFormData({
                name: category.name || '',
                description: category.description || '',
                parent_id: (category as any).parent_id || null,
                file_id: fileId || undefined,
            });

            if (fileId && fileUrl) {
                setUploadedImage({ id: String(fileId), url: fileUrl });
            } else if (fileId) {
                setUploadedImage({ id: String(fileId), url: '' });
            } else {
                setUploadedImage(null);
            }
        }
    }, [category, isEdit]);

    const handleChange = (field: string, value: any) => {
        setFormData(prev => ({
            ...prev,
            [field]: value
        }));
    };

    const handleFileUpload = async (file: File) => {
        try {
            const result = await uploadFile(file);
            const fileId = parseInt(result.id);
            setUploadedImage({
                id: result.id,
                url: result.url
            });
            setFormData(prev => ({
                ...prev,
                file_id: fileId
            }));
            return result;
        } catch (error) {
            console.error('Upload error:', error);
            throw error;
        }
    };

    const handleFileRemove = (fileId: string) => {
        setUploadedImage(null);
        setFormData(prev => ({
            ...prev,
            file_id: undefined
        }));
        deleteFile(fileId);
    };

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

        try {
            if (isEdit) {
                await updateMutation.mutateAsync({
                    id: parseInt(id!),
                    ...formData
                });
            } else {
                await createMutation.mutateAsync(formData);
            }
        } catch (error) {
            console.error('Error saving category:', error);
        }
    };

    const handleBack = () => {
        navigate('/categories');
    };

    if (isEdit && isLoadingCategory) {
        return (
            <PageContainer>
                <div className="space-y-6 animate-pulse">
                    <div className="h-8 bg-gray-200 dark:bg-gray-700 rounded w-48"></div>
                    <div className="card p-6 space-y-6">
                        {[...Array(4)].map((_, i) => (
                            <div key={i}>
                                <div className="h-4 bg-gray-200 dark:bg-gray-700 rounded w-32 mb-2"></div>
                                <div className="h-10 bg-gray-200 dark:bg-gray-700 rounded"></div>
                            </div>
                        ))}
                    </div>
                </div>
            </PageContainer>
        );
    }

    const backButton = (
        <Button
            variant="secondary"
            onClick={handleBack}
            className="flex items-center gap-2"
        >
            <ArrowRight className="h-4 w-4" />
            بازگشت
        </Button>
    );

    return (
        <PageContainer className="max-w-2xl mx-auto">
            <FormHeader
                title={isEdit ? 'ویرایش دسته‌بندی' : 'ایجاد دسته‌بندی جدید'}
                subtitle={isEdit ? 'ویرایش اطلاعات دسته‌بندی' : 'اطلاعات دسته‌بندی جدید را وارد کنید'}
                backButton={backButton}
            />

            <div className="card p-4 sm:p-6">
                <form onSubmit={handleSubmit} className="space-y-4 sm:space-y-6">
                    <div>
                        <Label htmlFor="name">نام دسته‌بندی</Label>
                        <Input
                            id="name"
                            type="text"
                            value={formData.name}
                            onChange={(e) => handleChange('name', e.target.value)}
                            placeholder="نام دسته‌بندی را وارد کنید"
                            required
                        />
                    </div>

                    <div>
                        <Label htmlFor="description">توضیحات</Label>
                        <textarea
                            id="description"
                            value={formData.description}
                            onChange={(e) => handleChange('description', e.target.value)}
                            placeholder="توضیحات دسته‌بندی"
                            rows={4}
                            className="input resize-none"
                        />
                    </div>

                    <div>
                        <FileUploader
                            onUpload={handleFileUpload}
                            onRemove={handleFileRemove}
                            acceptedTypes={['image/*']}
                            maxFileSize={5 * 1024 * 1024}
                            maxFiles={1}
                            mode="single"
                            label="تصویر دسته‌بندی"
                            description="تصویر دسته‌بندی را انتخاب کنید (حداکثر 5MB)"
                            onUploadStart={() => setIsUploading(true)}
                            onUploadComplete={() => setIsUploading(false)}
                            initialFiles={uploadedImage ? [{ id: uploadedImage.id, url: uploadedImage.url }] : []}
                        />
                    </div>

                    <div className="flex flex-col space-y-3 sm:flex-row sm:justify-end sm:space-y-0 sm:space-x-3 sm:space-x-reverse pt-4 border-t border-gray-200 dark:border-gray-700">
                        <Button
                            type="button"
                            variant="secondary"
                            onClick={handleBack}
                            className="w-full sm:w-auto"
                        >
                            انصراف
                        </Button>
                        <Button
                            type="submit"
                            loading={createMutation.isPending || updateMutation.isPending}
                            disabled={isUploading}
                            className="w-full sm:w-auto"
                        >
                            {isEdit ? 'ویرایش' : 'ایجاد'}
                        </Button>
                    </div>
                </form>
            </div>
        </PageContainer>
    );
};

export default CategoryFormPage; 