import { useEffect, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useForm } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
import * as yup from 'yup';
import { useProduct, useCreateProduct, useUpdateProduct } from '../core/_hooks';
import { useCategories } from '../../categories/core/_hooks';
import { useProductOptions } from '../../product-options/core/_hooks';
import { useFileUpload, useFileDelete } from '../../../hooks/useFileUpload';
import { ProductFormData, ProductImage, ProductVariantFormData, PRODUCT_TYPES, PRODUCT_TYPE_LABELS } from '../core/_models';
import { MultiSelectAutocomplete } from "@/components/ui/MultiSelectAutocomplete";
import { Button } from "@/components/ui/Button";
import { Input } from "@/components/ui/Input";
import { FileUploader } from "@/components/ui/FileUploader";
import { VariantManager } from "@/components/ui/VariantManager";
import { ArrowRight, X } from "lucide-react";
import { FormHeader, PageContainer, Label } from '../../../components/ui/Typography';
import { FormSection } from '@/components/forms/FormSection';
import { FormActions } from '@/components/forms/FormActions';
import { createNumberTransform, createOptionalNumberTransform, convertPersianNumbersInObject } from '../../../utils/numberUtils';
import { API_GATE_WAY, API_ROUTES } from '@/constant/routes';
import { toast } from "react-hot-toast";

const productSchema = yup.object({
    name: yup.string().required('نام محصول الزامی است').min(2, 'نام محصول باید حداقل 2 کاراکتر باشد'),
    description: yup.string(),
    design_style: yup.string(),
    enabled: yup.boolean().default(true),
    total_sold: yup.number()
        .transform(createNumberTransform())
        .min(0, 'تعداد فروخته شده نمی‌تواند منفی باشد')
        .optional(),
    type: yup.number().oneOf([0, 1, 2, 3]).default(1),
    variant_attribute_name: yup.string().optional(),
    category_ids: yup.array().of(yup.number()).default([]),
    product_option_id: yup.number().transform(createOptionalNumberTransform()).nullable(),
    file_ids: yup.array().of(yup.object()).default([]),
    variants: yup.array().default([]),
    explorer_file_ids: yup.array().of(yup.object()).default([]),
    is_delete_latest_explorer_files: yup.boolean().optional(),
    product_cover_image_id: yup.string().optional(),
    sku: yup.string().optional(),
});

const toPublicUrl = (img: any): ProductImage => {
    const rawUrl: string = img?.url || img?.file_url || img?.fileUrl || '';
    const serveKey: string | undefined = img?.serve_key || img?.serveKey;
    const url = serveKey
        ? `${API_GATE_WAY}/${API_ROUTES.DOWNLOAD_FILE(serveKey)}`
        : rawUrl?.startsWith('http')
            ? rawUrl
            : rawUrl
                ? `${API_GATE_WAY}${rawUrl.startsWith('/') ? '' : '/'}${rawUrl}`
                : '';
    return {
        id: (img?.id ?? img?.file_id ?? img?.FileID ?? img).toString(),
        url,
        alt: img?.alt || img?.original_name || '',
        order: img?.order ?? 0,
        type: img?.mime_type || img?.type || img?.file_type,
        mime_type: img?.mime_type || img?.file_type,
        size: img?.size,
    };
};

const mapExplorerFiles = (entries: any[]): ProductImage[] => {
    if (!entries || !Array.isArray(entries)) {
        return [];
    }
    return entries.map((entry, index) => {
        if (entry?.file) {
            const media = toPublicUrl(entry.file);
            return { ...media, order: index };
        }
        if (entry?.file_id) {
            const normalized = toPublicUrl({
                ...entry,
                id: entry.file_id,
                url: entry.file_url || entry.url,
                file_url: entry.file_url || entry.url,
                mime_type: entry.mime_type || entry.file_type,
                type: entry.file_type || entry.type,
                original_name: entry.name || entry.original_name,
            });
            return { ...normalized, order: index };
        }
        if (entry?.FileID) {
            const normalized = toPublicUrl({
                ...entry,
                id: entry.FileID,
                url: entry.file_url || entry.url,
                file_url: entry.file_url || entry.url,
            });
            return { ...normalized, order: index };
        }
        if (typeof entry === 'number' || typeof entry === 'string') {
            const normalized = toPublicUrl(entry);
            return { ...normalized, order: index };
        }
        const normalized = toPublicUrl(entry);
        return { ...normalized, order: index };
    });
};

const ProductFormPage = () => {
    const navigate = useNavigate();
    const { id } = useParams<{ id: string }>();
    const isEdit = !!id;

    const [uploadedImages, setUploadedImages] = useState<ProductImage[]>([]);
    const [isUploading, setIsUploading] = useState(false);
    const [explorerFiles, setExplorerFiles] = useState<ProductImage[]>([]);
    const [isExplorerUploading, setIsExplorerUploading] = useState(false);
    const [isDeleteExplorerFiles, setIsDeleteExplorerFiles] = useState(false);
    const [initialExplorerIds, setInitialExplorerIds] = useState<string[]>([]);
    const [initialCoverId, setInitialCoverId] = useState<number | null>(null);

    const { data: product, isLoading: isLoadingProduct } = useProduct(id || '', isEdit);
    const { data: categories, isLoading: isLoadingCategories } = useCategories();
    const { data: productOptions, isLoading: isLoadingProductOptions } = useProductOptions();
    const { mutate: createProduct, isPending: isCreating } = useCreateProduct();
    const { mutate: updateProduct, isPending: isUpdating } = useUpdateProduct();
    const { mutateAsync: uploadFile } = useFileUpload();
    const { mutate: deleteFile } = useFileDelete();

    const isLoading = isCreating || isUpdating;

    const {
        register,
        handleSubmit,
        formState: { errors, isValid, isDirty },
        setValue,
        watch,
        reset,
        control
    } = useForm<ProductFormData>({
        resolver: yupResolver(productSchema) as any,
        mode: 'onChange',
        defaultValues: {
            name: '',
            description: '',
            design_style: '',
            enabled: true,
            total_sold: undefined,
            type: 1,
            variant_attribute_name: '',
            category_ids: [],
            product_option_id: undefined,
            file_ids: [],
            variants: [],
            explorer_file_ids: [],
            is_delete_latest_explorer_files: false,
            product_cover_image_id: undefined,
            sku: undefined
        }
    });

    const formValues = watch();
    const coverId = watch('product_cover_image_id') as string | undefined;

    useEffect(() => {
        if (isEdit && product) {
            console.log('Product data in edit mode:', product);

            // Extract category IDs - handle different API response formats
            let categoryIds: number[] = [];
            if (product.category_ids && product.category_ids.length > 0) {
                categoryIds = product.category_ids;
            } else if (product.categories && product.categories.length > 0) {
                categoryIds = product.categories.map(cat => cat.id);
            } else if (product.product_categories && product.product_categories.length > 0) {
                categoryIds = product.product_categories.map(cat => cat.id);
            }

            console.log('✅ Successfully extracted category IDs:', categoryIds);

            // تبدیل variants از ProductVariant به ProductVariantFormData - handle both variants and product_variants
            const variants = product.variants && product.variants.length > 0 ? product.variants : ((product as any).product_variants || []);
            const formVariants = variants.map((variant: any) => ({
                id: variant.id,
                enabled: variant.enabled,
                fee_percentage: variant.fee_percentage,
                profit_percentage: variant.profit_percentage,
                tax_percentage: variant.tax_percentage || 0,
                stock_limit: variant.stock_limit,
                stock_managed: variant.stock_managed,
                stock_number: variant.stock_number,
                weight: variant.weight,
                product_option_id: variant.product_option_id || undefined,
                attributes: variant.attributes || {},
                meta: variant.meta || {},
                file_ids: (variant.file_ids && variant.file_ids.length > 0 ? variant.file_ids : (variant as any).files || []),
                gold_price_per_gram: variant.gold_price_per_gram || undefined,
                factory_fee_percentage: variant.factory_fee_percentage || undefined
            }));

            console.log('✅ Successfully processed variants:', formVariants.length);

            // استخراج نام ویژگی Variant از فیلد variant_attributes
            let variantAttributeName = '';
            if ((product as any).variant_attributes && Array.isArray((product as any).variant_attributes) && (product as any).variant_attributes.length > 0) {
                const firstAttribute = (product as any).variant_attributes[0];
                if (firstAttribute && firstAttribute.name) {
                    variantAttributeName = firstAttribute.name;
                }
            }
            // Fallback to direct field if exists
            if (!variantAttributeName && (product as any).variant_attribute_name) {
                variantAttributeName = (product as any).variant_attribute_name;
            }

            reset({
                name: product.name,
                description: product.description || '',
                design_style: product.design_style || '',
                enabled: product.enabled,
                total_sold: product.total_sold || 0,
                type: 1,
                variant_attribute_name: variantAttributeName,
                category_ids: categoryIds,
                product_option_id: product.product_option_id || undefined,
                file_ids: (product.file_ids && product.file_ids.length > 0 ? product.file_ids : (product as any).files || []),
                variants: formVariants,
                product_cover_image_id: (product as any).product_cover_image_id ? (product as any).product_cover_image_id.toString() : undefined,
                sku: product.sku || undefined
            });
            const initialImages = (product.file_ids && product.file_ids.length > 0 ? product.file_ids : (product as any).files || []);
            const normalizedImages: ProductImage[] = (initialImages || []).map(toPublicUrl);
            setUploadedImages(normalizedImages);
            setValue('file_ids', normalizedImages, { shouldValidate: true, shouldDirty: false });
            const explorerSource =
                (product as any).explorer_files && (product as any).explorer_files.length > 0
                    ? (product as any).explorer_files
                    : (product as any).explorer_file_ids || [];
            const normalizedExplorer = mapExplorerFiles(explorerSource);
            setExplorerFiles(normalizedExplorer);
            setValue('explorer_file_ids', normalizedExplorer, { shouldValidate: true, shouldDirty: false });
            setIsDeleteExplorerFiles(false);
            setInitialExplorerIds(normalizedExplorer.map(item => item.id?.toString?.() || ''));
            const coverId = (product as any).product_cover_image_id;
            setInitialCoverId(coverId ? Number(coverId) : null);
        }
    }, [isEdit, product, reset]);

    const handleFileUpload = async (file: File) => {
        try {
            const result = await uploadFile(file);

            setUploadedImages(prev => {
                const newImage: ProductImage = {
                    id: result.id,
                    url: result.url,
                    alt: file.name,
                    order: prev.length,
                    type: result.mimeType || file.type
                };
                const updated = [...prev, newImage];
                setValue('file_ids', updated, { shouldValidate: true, shouldDirty: true });
                return updated;
            });

            return result;
        } catch (error: any) {
            toast.error(error?.message || 'خطا در آپلود فایل');
            throw error;
        }
    };

    const handleFileRemove = (fileId: string) => {
        const updatedImages = uploadedImages.filter(img => img.id !== fileId);
        setUploadedImages(updatedImages);
        setValue('file_ids', updatedImages, { shouldValidate: true, shouldDirty: true });
        if (coverId === fileId) {
            setValue('product_cover_image_id', undefined, { shouldValidate: true, shouldDirty: true });
        }
        deleteFile(fileId);
    };

    const handleExplorerUpload = async (file: File) => {
        try {
            const result = await uploadFile(file);
            setExplorerFiles(prev => {
                const newImage: ProductImage = {
                    id: result.id,
                    url: result.url,
                    alt: file.name,
                    order: prev.length,
                    type: result.mimeType || file.type
                };
                const updated = [...prev, newImage];
                setValue('explorer_file_ids', updated, { shouldValidate: true, shouldDirty: true });
                return updated;
            });
            return result;
        } catch (error: any) {
            toast.error(error?.message || 'خطا در آپلود فایل');
            throw error;
        }
    };

    const handleExplorerRemove = (fileId: string) => {
        const updatedImages = explorerFiles.filter(img => img.id !== fileId);
        setExplorerFiles(updatedImages);
        setValue('explorer_file_ids', updatedImages, { shouldValidate: true, shouldDirty: true });
        deleteFile(fileId);
    };



    const onSubmit = (data: any) => {
        const convertedData = convertPersianNumbersInObject(data);

        const validImageIds = uploadedImages
            .map(img => {
                const numericId = Number(img.id);
                return isNaN(numericId) ? null : numericId;
            })
            .filter(id => id !== null);

        const validExplorerIds = explorerFiles
            .filter(img => !initialExplorerIds.includes(img.id?.toString?.() || ''))
            .map(img => {
                const numericId = Number(img.id);
                return isNaN(numericId) ? null : numericId;
            })
            .filter(id => id !== null);

        const selectedCoverId = convertedData.product_cover_image_id ? Number(convertedData.product_cover_image_id) : null;
        const hasCover = selectedCoverId !== null && !isNaN(selectedCoverId);

        const baseSubmitData = {
            name: convertedData.name,
            description: convertedData.description || '',
            design_style: convertedData.design_style || '',
            enabled: convertedData.enabled,
            total_sold: convertedData.total_sold || 0,
            type: 1,
            variant_attribute_name: convertedData.variant_attribute_name || '',
            attributes: {},
            category_ids: convertedData.category_ids.length > 0 ? convertedData.category_ids : [],
            product_option_id: convertedData.product_option_id || null,
            file_ids: validImageIds,
            sku: convertedData.sku || undefined,
        };

        const submitBaseData = {
            ...baseSubmitData,
            explorer_file_ids: validExplorerIds,
        };

        console.log('Submitting product data:', baseSubmitData);
        console.log('Original data:', data);
        console.log('Converted data:', convertedData);

        if (isEdit && id) {
            // برای update، variants باید شامل ID باشه
            const updateVariants = data.variants?.map((variant: any) => ({
                id: variant.id || 0,
                enabled: variant.enabled,
                fee_percentage: variant.fee_percentage,
                profit_percentage: variant.profit_percentage,
                tax_percentage: variant.tax_percentage || 0,
                stock_limit: variant.stock_limit,
                stock_managed: variant.stock_managed,
                stock_number: variant.stock_number,
                weight: variant.weight,
                file_ids: Array.isArray(variant.file_ids) ? variant.file_ids.map((file: any) => Number(typeof file === 'object' ? file.id : file)).filter((id: number) => !isNaN(id)) : [],
                attributes: variant.attributes && convertedData.variant_attribute_name && variant.attributes[convertedData.variant_attribute_name] !== undefined ? { [convertedData.variant_attribute_name]: variant.attributes[convertedData.variant_attribute_name] } : {},
                meta: variant.meta && Object.keys(variant.meta).length > 0 ? variant.meta : {},
                gold_price_per_gram: variant.gold_price_per_gram || undefined,
                factory_fee_percentage: variant.factory_fee_percentage || undefined
            })) || [];

            const updatePayload = {
                id: parseInt(id),
                ...submitBaseData,
                variants: updateVariants,
                is_delete_latest_explorer_files: isDeleteExplorerFiles
            };
            if (hasCover && selectedCoverId !== initialCoverId) {
                (updatePayload as any).product_cover_image_id = selectedCoverId;
            }
            updateProduct(updatePayload, {
                onSuccess: () => {
                    navigate('/products');
                }
            });
        } else {
            // برای create، variants نباید ID داشته باشه
            const createVariants = data.variants?.map((variant: any) => ({
                enabled: variant.enabled,
                fee_percentage: variant.fee_percentage,
                profit_percentage: variant.profit_percentage,
                tax_percentage: variant.tax_percentage || 0,
                stock_limit: variant.stock_limit,
                stock_managed: variant.stock_managed,
                stock_number: variant.stock_number,
                weight: variant.weight,
                file_ids: Array.isArray(variant.file_ids) ? variant.file_ids.map((file: any) => Number(typeof file === 'object' ? file.id : file)).filter((id: number) => !isNaN(id)) : [],
                attributes: variant.attributes && convertedData.variant_attribute_name && variant.attributes[convertedData.variant_attribute_name] !== undefined ? { [convertedData.variant_attribute_name]: variant.attributes[convertedData.variant_attribute_name] } : {},
                meta: variant.meta && Object.keys(variant.meta).length > 0 ? variant.meta : {},
                gold_price_per_gram: variant.gold_price_per_gram || undefined,
                factory_fee_percentage: variant.factory_fee_percentage || undefined
            })) || [];

            const createPayload: any = {
                ...submitBaseData,
                variants: createVariants
            };
            if (hasCover) {
                createPayload.product_cover_image_id = selectedCoverId;
            }

            createProduct(createPayload, {
                onSuccess: () => {
                    navigate('/products');
                }
            });
        }
    };

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

    useEffect(() => {
        if (!coverId && uploadedImages.length > 0 && !initialCoverId) {
            setValue('product_cover_image_id', uploadedImages[0].id, { shouldValidate: true, shouldDirty: false });
        }
    }, [coverId, uploadedImages, setValue, initialCoverId]);

    if (isEdit && isLoadingProduct) {
        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(8)].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 categoryOptions = (categories || []).map(category => ({
        id: category.id,
        title: category.name,
        description: category.description
    }));

    const productOptionOptions = (productOptions || []).map(option => ({
        id: option.id,
        title: option.title,
        description: `تعداد گزینه‌ها: ${(option.options || []).length}`
    }));



    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-6xl mx-auto">
            <FormHeader
                title={isEdit ? 'ویرایش محصول' : 'ایجاد محصول جدید'}
                subtitle={isEdit ? 'ویرایش اطلاعات محصول' : 'اطلاعات محصول جدید را وارد کنید'}
                backButton={backButton}
            />

            {/* Form */}
            <div className="bg-white dark:bg-gray-800 shadow-sm border border-gray-200 dark:border-gray-700 rounded-lg p-6">
                <form onSubmit={handleSubmit(onSubmit)} className="space-y-8">
                    <FormSection title="اطلاعات پایه">
                        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                            <div className="md:col-span-2">
                                <Input
                                    label="نام محصول"
                                    {...register('name')}
                                    error={errors.name?.message}
                                    placeholder="نام محصول را وارد کنید"
                                />
                            </div>

                            <div className="flex items-center space-x-3 space-x-reverse">
                                <input
                                    type="checkbox"
                                    {...register('enabled')}
                                    className="w-4 h-4 text-primary-600 bg-gray-100 border-gray-300 rounded focus:ring-primary-500 dark:focus:ring-primary-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600"
                                />
                                <label className="text-sm font-medium text-gray-700 dark:text-gray-300">
                                    محصول فعال باشد
                                </label>
                            </div>



                            <Input
                                label="تعداد فروخته شده"
                                numeric
                                {...register('total_sold')}
                                error={errors.total_sold?.message}
                                placeholder="مثال: ۱۰۰"
                            />

                            <Input
                                label="استایل طراحی"
                                {...register('design_style')}
                                error={errors.design_style?.message}
                                placeholder="مدرن، کلاسیک، مینیمال..."
                            />

                            <Input
                                label="نام ویژگی Variant"
                                {...register('variant_attribute_name')}
                                error={errors.variant_attribute_name?.message}
                                placeholder="مثال: آبکاری، رنگ، سایز..."
                            />

                            <Input
                                label="SKU"
                                {...register('sku')}
                                error={errors.sku?.message}
                                placeholder="مثال: RING-001"
                            />

                            <div className="md:col-span-2">
                                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                                    توضیحات
                                </label>
                                <textarea
                                    {...register('description')}
                                    rows={4}
                                    className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-1 focus:ring-primary-500 dark:bg-gray-700 dark:text-gray-100"
                                    placeholder="توضیحات کامل محصول را وارد کنید..."
                                />
                                {errors.description && (
                                    <p className="text-red-500 text-sm mt-1">{errors.description.message}</p>
                                )}
                            </div>
                        </div>
                    </FormSection>

                    <FormSection title="دسته‌بندی و گزینه‌ها">
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                            <MultiSelectAutocomplete
                                label="دسته‌بندی‌ها"
                                options={categoryOptions}
                                selectedValues={watch('category_ids') || []}
                                onChange={(values) => setValue('category_ids', values, { shouldValidate: true, shouldDirty: true })}
                                placeholder="دسته‌بندی‌ها را انتخاب کنید..."
                                isLoading={isLoadingCategories}
                            />

                            <div>
                                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                                    ویژگی های محصول و نحوه نگه داری
                                </label>
                                {isLoadingProductOptions ? (
                                    <div className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-gray-50 dark:bg-gray-700 text-gray-500 dark:text-gray-400">
                                        در حال بارگذاری گزینه‌ها...
                                    </div>
                                ) : (
                                    <select
                                        {...register('product_option_id')}
                                        className="w-full px-3 py-3 text-base border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-primary-500 dark:bg-gray-700 dark:text-gray-100 transition-all duration-200"
                                    >
                                        <option value="">بدون گزینه</option>
                                        {productOptionOptions.map((option) => (
                                            <option key={option.id} value={option.id}>
                                                {option.title} - {option.description}
                                            </option>
                                        ))}
                                    </select>
                                )}
                                {productOptionOptions.length === 0 && !isLoadingProductOptions && (
                                    <p className="text-amber-600 text-sm mt-1">هیچ گزینه محصولی یافت نشد</p>
                                )}
                                {errors.product_option_id && (
                                    <p className="text-red-500 text-sm mt-1">{errors.product_option_id.message}</p>
                                )}
                            </div>
                        </div>
                    </FormSection>

                    <FormSection title="تصاویر محصول">

                        <FileUploader
                            onUpload={handleFileUpload}
                            onRemove={handleFileRemove}
                            mode="multi"
                            label=""
                            description="فایل‌های محصول را آپلود کنید"
                            onUploadStart={() => setIsUploading(true)}
                            onUploadComplete={() => setIsUploading(false)}
                        />

                        {uploadedImages.length > 0 && (
                            <div className="mt-6">
                                <h4 className="text-sm font-medium text-gray-700 dark:text-gray-300 mb-3">
                                    تصاویر آپلود شده ({uploadedImages.length})
                                </h4>
                                <div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-4">
                                    {uploadedImages.map((image, index) => (
                                        <div key={image.id} className="relative group">
                                            {image.type?.startsWith('video') ? (
                                                <video
                                                    src={image.url}
                                                    className="w-full h-24 object-cover rounded-lg border border-gray-200 dark:border-gray-600"
                                                    controls
                                                    muted
                                                />
                                            ) : (
                                                <img
                                                    src={image.url}
                                                    alt={image.alt || `تصویر ${index + 1}`}
                                                    className="w-full h-24 object-cover rounded-lg border border-gray-200 dark:border-gray-600"
                                                />
                                            )}
                                            <button
                                                type="button"
                                                onClick={() => handleFileRemove(image.id)}
                                                className="absolute -top-2 -right-2 w-6 h-6 bg-red-500 text-white rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity"
                                            >
                                                <X className="h-3 w-3" />
                                            </button>
                                            <button
                                                type="button"
                                                onClick={() => setValue('product_cover_image_id', image.id, { shouldValidate: true, shouldDirty: true })}
                                                className={`absolute -bottom-2 left-1 text-xs px-2 py-0.5 rounded ${coverId === image.id ? 'bg-primary-600 text-white' : 'bg-gray-200 text-gray-700 dark:bg-gray-700 dark:text-gray-200'}`}
                                            >
                                                کاور
                                            </button>
                                        </div>
                                    ))}
                                </div>
                            </div>
                        )}
                    </FormSection>

                    <FormSection title="فایل‌های Explorer">
                        <FileUploader
                            onUpload={handleExplorerUpload}
                            onRemove={handleExplorerRemove}
                            mode="multi"
                            label=""
                            description="فایل‌های Explorer را آپلود کنید"
                            onUploadStart={() => setIsExplorerUploading(true)}
                            onUploadComplete={() => setIsExplorerUploading(false)}
                        />
                        {explorerFiles.length > 0 && (
                            <div className="mt-6">
                                <h4 className="text-sm font-medium text-gray-700 dark:text-gray-300 mb-3">
                                    فایل‌های Explorer ({explorerFiles.length})
                                </h4>
                                <div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-4">
                                    {explorerFiles.map((file, index) => (
                                        <div key={file.id} className="relative group">
                                            {file.url ? (
                                                file.type?.startsWith('video') ? (
                                                    <video
                                                        src={file.url}
                                                        className="w-full h-24 object-cover rounded-lg border border-gray-200 dark:border-gray-600"
                                                        controls
                                                        muted
                                                    />
                                                ) : (
                                                    <img
                                                        src={file.url}
                                                        alt={file.alt || `فایل ${index + 1}`}
                                                        className="w-full h-24 object-cover rounded-lg border border-gray-200 dark:border-gray-600"
                                                    />
                                                )
                                            ) : (
                                                <div className="w-full h-24 rounded-lg border border-dashed border-gray-300 dark:border-gray-600 flex items-center justify-center text-xs text-gray-500 dark:text-gray-400">
                                                    پیش‌نمایش در دسترس نیست
                                                </div>
                                            )}
                                            <button
                                                type="button"
                                                onClick={() => handleExplorerRemove(file.id)}
                                                className="absolute -top-2 -right-2 w-6 h-6 bg-red-500 text-white rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity"
                                            >
                                                <X className="h-3 w-3" />
                                            </button>
                                        </div>
                                    ))}
                                </div>
                            </div>
                        )}
                        {isEdit && (
                            <div className="flex items-center gap-2 mt-4">
                                <input
                                    type="checkbox"
                                    className="w-4 h-4 text-primary-600 bg-gray-100 border-gray-300 rounded focus:ring-primary-500"
                                    checked={isDeleteExplorerFiles}
                                    onChange={(e) => setIsDeleteExplorerFiles(e.target.checked)}
                                />
                                <span className="text-sm text-gray-700 dark:text-gray-300">
                                    حذف فایل‌های Explorer قبلی و جایگزینی با فایل‌های جدید
                                </span>
                            </div>
                        )}
                    </FormSection>

                    <FormSection title="مدیریت Variants">
                        <VariantManager
                            variants={watch('variants') || []}
                            onChange={(variants) => setValue('variants', variants, { shouldValidate: true, shouldDirty: true })}
                            productOptions={productOptionOptions}
                            variantAttributeName={watch('variant_attribute_name')}
                        />
                    </FormSection>

                    {/* Preview */}
                    {formValues.name && (
                        <div className="border border-gray-200 dark:border-gray-600 rounded-lg p-4 bg-gray-50 dark:bg-gray-700">
                            <h3 className="text-sm font-medium text-gray-900 dark:text-gray-100 mb-3">
                                پیش‌نمایش محصول
                            </h3>
                            <div className="flex gap-4">
                                {uploadedImages.length > 0 && (
                                    uploadedImages[0].type?.startsWith('video') ? (
                                        <video
                                            src={uploadedImages[0].url}
                                            className="w-20 h-20 object-cover rounded-lg border"
                                            controls
                                            muted
                                        />
                                    ) : (
                                        <img
                                            src={uploadedImages[0].url}
                                            alt={formValues.name}
                                            className="w-20 h-20 object-cover rounded-lg border"
                                        />
                                    )
                                )}
                                <div className="flex-1 space-y-2">
                                    <div className="text-sm text-gray-600 dark:text-gray-400">
                                        <strong>نام:</strong> {formValues.name}
                                    </div>
                                    <div className="text-sm text-gray-600 dark:text-gray-400">
                                        <strong>نوع:</strong> {PRODUCT_TYPE_LABELS[formValues.type as keyof typeof PRODUCT_TYPE_LABELS]}
                                    </div>
                                    <div className="text-sm text-gray-600 dark:text-gray-400">
                                        <strong>تعداد فروخته شده:</strong> {formValues.total_sold}
                                    </div>
                                    {formValues.design_style && (
                                        <div className="text-sm text-gray-600 dark:text-gray-400">
                                            <strong>استایل:</strong> {formValues.design_style}
                                        </div>
                                    )}
                                    {formValues.variant_attribute_name && (
                                        <div className="text-sm text-gray-600 dark:text-gray-400">
                                            <strong>نام ویژگی Variant:</strong> {formValues.variant_attribute_name}
                                        </div>
                                    )}
                                    {formValues.category_ids && formValues.category_ids.length > 0 && (
                                        <div className="text-sm text-gray-600 dark:text-gray-400">
                                            <strong>دسته‌بندی‌ها:</strong> {
                                                categories?.filter(c => formValues.category_ids.includes(c.id))
                                                    .map(c => c.name).join(', ')
                                            }
                                        </div>
                                    )}
                                    {formValues.variants && formValues.variants.length > 0 && (
                                        <div className="text-sm text-gray-600 dark:text-gray-400">
                                            <strong>تعداد Variants:</strong> {formValues.variants.length} نوع
                                        </div>
                                    )}

                                    <div className="flex items-center gap-2">
                                        {formValues.enabled && (
                                            <span className="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-green-100 text-green-800">
                                                فعال
                                            </span>
                                        )}
                                        {!formValues.enabled && (
                                            <span className="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-red-100 text-red-800">
                                                غیرفعال
                                            </span>
                                        )}
                                    </div>
                                </div>
                            </div>
                        </div>
                    )}

                    <FormActions
                        onCancel={handleBack}
                        cancelLabel="انصراف"
                        submitLabel={isEdit ? 'به‌روزرسانی' : 'ایجاد محصول'}
                        isLoading={isLoading}
                        isDisabled={!isValid || isLoading || isUploading || isExplorerUploading}
                    />
                </form>
            </div>

            {/* Help Section */}
            <div className="bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg p-4">
                <h3 className="text-sm font-medium text-blue-900 dark:text-blue-100 mb-2">
                    راهنما
                </h3>
                <ul className="text-sm text-blue-700 dark:text-blue-300 space-y-1">
                    <li>• نام محصول باید واضح و جذاب باشد</li>
                    <li>• میتوانید چندین دسته‌بندی برای محصول انتخاب کنید</li>
                    <li>• گزینه محصول برای محصولات متغیر (با رنگ، سایز و...) استفاده میشود</li>
                    <li>• نام ویژگی Variant برای تعیین کلید ویژگی در هر variant استفاده می‌شود</li>
                    <li>• Variants برای انواع مختلف محصول استفاده میشود</li>
                    <li>• اولین تصویر به عنوان تصویر اصلی محصول استفاده می‌شود</li>
                </ul>
            </div>
        </PageContainer>
    );
};

export default ProductFormPage; 