import { useEffect, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useForm, Controller } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
import * as yup from 'yup';
import { parseFormattedNumber } from '@/utils/numberUtils';
import { useDiscountCode, useCreateDiscountCode, useUpdateDiscountCode } from '../core/_hooks';
import { CreateDiscountCodeRequest } from '../core/_models';
import { Button } from "@/components/ui/Button";
import { Input } from "@/components/ui/Input";
import { MultiSelectAutocomplete, Option } from "@/components/ui/MultiSelectAutocomplete";
import { SingleSelectAutocomplete } from "@/components/ui/SingleSelectAutocomplete";
import { JalaliDateTimePicker } from "@/components/ui/JalaliDateTimePicker";
import { FormHeader, PageContainer, Label, SectionTitle } from '../../../components/ui/Typography';
import { ArrowRight, BadgePercent, Calendar, Settings, Users, Tag, Info } from 'lucide-react';
import { useUsers, useSearchUsers } from '../../users-admin/core/_hooks';
import { useSearchProducts } from '../../products/core/_hooks';
import { useSearchCategories } from '../../categories/core/_hooks';
import { formatDateTimeLocal } from '../../../utils/formatters';

const schema = yup.object({
    code: yup.string().min(3, 'کد باید حداقل ۳ کاراکتر باشد').max(50, 'کد نباید بیشتر از ۵۰ کاراکتر باشد').required('کد الزامی است'),
    name: yup.string().min(1, 'نام الزامی است').max(100, 'نام نباید بیشتر از ۱۰۰ کاراکتر باشد').required('نام الزامی است'),
    description: yup.string().max(500, 'توضیحات نباید بیشتر از ۵۰۰ کاراکتر باشد').nullable(),
    type: yup.mixed<'percentage' | 'fixed' | 'fee_percentage'>().oneOf(['percentage', 'fixed', 'fee_percentage']).required('نوع الزامی است'),
    value: yup
        .number()
        .transform((val, original) => parseFormattedNumber(original) as any)
        .typeError('مقدار نامعتبر است')
        .required('مقدار الزامی است')
        .min(0.01, 'مقدار باید بیشتر از صفر باشد')
        .max(999999, 'مقدار نباید بیشتر از ۹۹۹,۹۹۹ باشد'),
    status: yup.mixed<'active' | 'inactive'>().oneOf(['active', 'inactive']).required('وضعیت الزامی است'),
    application_level: yup.mixed<'invoice' | 'category' | 'product' | 'shipping' | 'product_fee'>().oneOf(['invoice', 'category', 'product', 'shipping', 'product_fee']).required('سطح اعمال الزامی است'),
    min_purchase_amount: yup
        .number()
        .transform((val, original) => parseFormattedNumber(original) as any)
        .min(0.01, 'مبلغ باید بیشتر از صفر باشد')
        .max(99999999, 'مبلغ نباید بیشتر از ۹۹,۹۹۹,۹۹۹ باشد')
        .nullable(),
    max_discount_amount: yup
        .number()
        .transform((val, original) => parseFormattedNumber(original) as any)
        .min(0.01, 'مبلغ باید بیشتر از صفر باشد')
        .max(99999999, 'مبلغ نباید بیشتر از ۹۹,۹۹۹,۹۹۹ باشد')
        .nullable(),
    usage_limit: yup.number().transform((v, o) => o === '' ? undefined : v).min(1, 'حداقل ۱ بار استفاده').max(999999, 'حداکثر ۹۹۹,۹۹۹ بار استفاده').nullable(),
    user_usage_limit: yup.number().transform((v, o) => o === '' ? undefined : v).min(1, 'حداقل ۱ بار استفاده').max(99999, 'حداکثر ۹۹,۹۹۹ بار استفاده').nullable(),
    single_use: yup.boolean().required('این فیلد الزامی است'),
    valid_from: yup.string().nullable(),
    valid_to: yup.string().nullable(),
});

// Convert input value (YYYY-MM-DDTHH:mm) to API format (YYYY-MM-DDTHH:mm:00Z)
const toApiDateTime = (value?: string): string | undefined => {
    if (!value) return undefined;
    const trimmed = value.slice(0, 16);
    return `${trimmed}:00Z`;
};

const DiscountCodeFormPage = () => {
    const navigate = useNavigate();
    const { id } = useParams();
    const isEdit = !!id;

    const [selectedProductIds, setSelectedProductIds] = useState<number[]>([]);
    const [selectedCategoryIds, setSelectedCategoryIds] = useState<number[]>([]);
    const [selectedApplicationLevel, setSelectedApplicationLevel] = useState<string>('invoice');
    const [selectedUserId, setSelectedUserId] = useState<number | undefined>();

    const { data: dc, isLoading: dcLoading } = useDiscountCode(id || '');
    const { mutate: create, isPending: creating } = useCreateDiscountCode();
    const { mutate: update, isPending: updating } = useUpdateDiscountCode();

    // Users list with pagination and search for dropdown
    const [userSearch, setUserSearch] = useState<string>('');
    const [userOffset, setUserOffset] = useState<number>(0);
    const [accumulatedUsers, setAccumulatedUsers] = useState<any[]>([]);
    const USERS_PAGE_SIZE = 20;

    const { data: searchResult, isLoading: usersLoading } = useSearchUsers({ limit: USERS_PAGE_SIZE, offset: userOffset, search_text: userSearch });

    // Products list with pagination and search for dropdown
    const [productSearch, setProductSearch] = useState<string>('');
    const [productPage, setProductPage] = useState<number>(1);
    const [accumulatedProducts, setAccumulatedProducts] = useState<any[]>([]);
    const PRODUCTS_PAGE_SIZE = 20;

    const { data: productSearchResult, isLoading: productsLoading } = useSearchProducts({
        search: productSearch,
        page: productPage,
        limit: PRODUCTS_PAGE_SIZE
    });

    // Categories list with pagination and search for dropdown
    const [categorySearch, setCategorySearch] = useState<string>('');
    const [categoryPage, setCategoryPage] = useState<number>(1);
    const [accumulatedCategories, setAccumulatedCategories] = useState<any[]>([]);
    const CATEGORIES_PAGE_SIZE = 20;

    const { data: categorySearchResult, isLoading: categoriesLoading } = useSearchCategories({
        search: categorySearch,
        page: categoryPage,
        limit: CATEGORIES_PAGE_SIZE
    });

    useEffect(() => {
        if (searchResult?.users) {
            setAccumulatedUsers(prev => {
                // If offset is 0 (new search), replace; otherwise append unique
                if (userOffset === 0) return searchResult.users;
                const byId = new Map(prev.map((u: any) => [u.id, u]));
                for (const u of searchResult.users) byId.set(u.id, u);
                return Array.from(byId.values());
            });
        }
    }, [searchResult, userOffset]);

    useEffect(() => {
        if (productSearchResult?.products) {
            setAccumulatedProducts(prev => {
                // If page is 1 (new search), replace; otherwise append unique
                if (productPage === 1) return productSearchResult.products;
                const byId = new Map(prev.map((p: any) => [p.id, p]));
                for (const p of productSearchResult.products) byId.set(p.id, p);
                return Array.from(byId.values());
            });
        }
    }, [productSearchResult, productPage]);

    useEffect(() => {
        if (categorySearchResult) {
            setAccumulatedCategories(prev => {
                // If page is 1 (new search), replace; otherwise append unique
                if (categoryPage === 1) return categorySearchResult;
                const byId = new Map(prev.map((c: any) => [c.id, c]));
                for (const c of categorySearchResult) byId.set(c.id, c);
                return Array.from(byId.values());
            });
        }
    }, [categorySearchResult, categoryPage]);

    // Convert users to options
    const userOptions: Option[] = (accumulatedUsers || []).map((user: any) => ({
        id: user.id,
        title: (user.first_name || user.last_name)
            ? `${user.first_name || ''} ${user.last_name || ''}`.trim()
            : user.phone_number,
        description: user.phone_number
    }));

    // Convert products to options
    const productOptions: Option[] = (accumulatedProducts || []).map((product: any) => ({
        id: product.id,
        title: product.name,
        description: product.description || `محصول #${product.id}`
    }));

    // Convert categories to options
    const categoryOptions: Option[] = (accumulatedCategories || []).map((category: any) => ({
        id: category.id,
        title: category.name,
        description: category.description || `دسته‌بندی #${category.id}`
    }));

    const { register, handleSubmit, control, formState: { errors, isValid }, reset, watch, setValue } = useForm<CreateDiscountCodeRequest>({
        resolver: yupResolver(schema as any),
        mode: 'onChange',
        defaultValues: { status: 'active', type: 'percentage', application_level: 'invoice', single_use: false }
    });

    const applicationLevel = watch('application_level');

    const handleApplicationLevelChange = (value: string) => {
        setSelectedApplicationLevel(value);
        setValue('application_level', value as any, { shouldDirty: true, shouldValidate: true });
        if (value !== 'product') {
            setSelectedProductIds([]);
        }
        if (value !== 'category') {
            setSelectedCategoryIds([]);
        }
    };

    useEffect(() => {
        if (applicationLevel && applicationLevel !== selectedApplicationLevel) {
            handleApplicationLevelChange(applicationLevel);
        }
    }, [applicationLevel]);

    useEffect(() => {
        if (isEdit && dc) {
            reset({
                code: dc.code,
                name: dc.name,
                description: dc.description,
                type: dc.type,
                value: dc.value,
                status: dc.status,
                application_level: dc.application_level,
                min_purchase_amount: dc.min_purchase_amount,
                max_discount_amount: dc.max_discount_amount,
                usage_limit: dc.usage_limit,
                user_usage_limit: dc.user_usage_limit,
                single_use: dc.single_use,
                valid_from: formatDateTimeLocal(dc.valid_from),
                valid_to: formatDateTimeLocal(dc.valid_to),
                user_restrictions: dc.user_restrictions,
                meta: dc.meta,
            });

            // Set selected user ID (first one if multiple)
            if (dc.user_restrictions?.user_ids && dc.user_restrictions.user_ids.length > 0) {
                setSelectedUserId(dc.user_restrictions.user_ids[0]);
            }

            // Set selected application level
            if (dc.application_level) {
                setSelectedApplicationLevel(
                    Array.isArray(dc.application_level)
                        ? dc.application_level[0]
                        : dc.application_level
                );
            }

            // Set selected product IDs
            if (dc.product_ids) {
                setSelectedProductIds(dc.product_ids);
            }

            // Set selected category IDs
            if (dc.category_ids) {
                setSelectedCategoryIds(dc.category_ids);
            }
        }
    }, [isEdit, dc, reset]);

    const onSubmit = (data: CreateDiscountCodeRequest) => {
        // Clean user_restrictions: remove new_users_only and loyal_users_only, and normalize dates
        const { new_users_only, loyal_users_only, ...cleanRestrictions } = (data.user_restrictions || {}) as any;

        const formData: CreateDiscountCodeRequest = {
            ...data,
            application_level: selectedApplicationLevel as any,
            valid_from: toApiDateTime(data.valid_from),
            valid_to: toApiDateTime(data.valid_to),
            user_restrictions: selectedUserId ? {
                ...cleanRestrictions,
                user_ids: [selectedUserId],
            } : cleanRestrictions.user_group ? cleanRestrictions : undefined,
            product_ids: selectedApplicationLevel === 'product' && selectedProductIds.length > 0 ? selectedProductIds : undefined,
            category_ids: selectedApplicationLevel === 'category' && selectedCategoryIds.length > 0 ? selectedCategoryIds : undefined,
        };

        if (isEdit && id) {
            update({ id: parseInt(id), ...formData }, { onSuccess: () => navigate('/discount-codes') });
        } else {
            create(formData, { onSuccess: () => navigate('/discount-codes') });
        }
    };

    if (isEdit && dcLoading) {
        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(6)].map((_, i) => (
                            <div key={i}>
                                <div className="h-4 bg-gray-200 dark:bg-gray-700 rounded w-24 mb-2"></div>
                                <div className="h-10 bg-gray-200 dark:bg-gray-700 rounded"></div>
                            </div>
                        ))}
                    </div>
                </div>
            </PageContainer>
        );
    }
    const isLoading = creating || updating;

    return (
        <PageContainer>
            <FormHeader
                title={isEdit ? 'ویرایش کد تخفیف' : 'ایجاد کد تخفیف'}
                subtitle="ایجاد و مدیریت کدهای تخفیف برای فروشگاه"
                actions={
                    <Button variant="secondary" onClick={() => navigate('/discount-codes')} className="flex items-center gap-2">
                        <ArrowRight className="h-4 w-4" />
                        بازگشت
                    </Button>
                }
            />

            <div className="max-w-5xl mx-auto">
                <form onSubmit={handleSubmit(onSubmit)} className="space-y-8">
                    {/* اطلاعات اصلی */}
                    <div className="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 overflow-hidden">
                        <div className="bg-gradient-to-r from-blue-50 to-indigo-50 dark:from-gray-700 dark:to-gray-600 px-6 py-4 border-b border-gray-200 dark:border-gray-700">
                            <div className="flex items-center gap-3">
                                <div className="p-2 bg-blue-100 dark:bg-blue-900 rounded-lg">
                                    <Tag className="h-5 w-5 text-blue-600 dark:text-blue-300" />
                                </div>
                                <SectionTitle>اطلاعات اصلی کد تخفیف</SectionTitle>
                            </div>
                        </div>
                        <div className="p-6">
                            <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                                <Input
                                    label="کد تخفیف"
                                    type="text"
                                    placeholder="مثال: SAVE20"
                                    error={errors.code?.message}
                                    {...register('code')}
                                    className="font-mono"
                                    data-testid="discount-code-input"
                                    aria-required="true"
                                    required
                                />
                                <Input
                                    label="نام نمایشی"
                                    type="text"
                                    placeholder="مثال: تخفیف ۲۰ درصدی"
                                    error={errors.name?.message}
                                    {...register('name')}
                                    data-testid="discount-name-input"
                                    aria-required="true"
                                    required
                                />
                                <div className="lg:col-span-2">
                                    <Label htmlFor="description">توضیحات</Label>
                                    <textarea
                                        id="description"
                                        placeholder="توضیحات کامل درباره این کد تخفیف..."
                                        className={`w-full px-4 py-3 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 resize-none h-24 transition-colors ${errors.description ? 'border-red-500 focus:ring-red-500 focus:border-red-500' : 'border-gray-300 dark:border-gray-600'} dark:bg-gray-700 dark:text-gray-100`}
                                        {...register('description' as const)}
                                        data-testid="discount-description-textarea"
                                    />
                                    {errors.description && <p className="text-sm text-red-600 dark:text-red-400 mt-1">{errors.description.message as string}</p>}
                                </div>
                            </div>
                        </div>
                    </div>

                    {/* تنظیمات تخفیف */}
                    <div className="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 overflow-hidden">
                        <div className="bg-gradient-to-r from-green-50 to-emerald-50 dark:from-gray-700 dark:to-gray-600 px-6 py-4 border-b border-gray-200 dark:border-gray-700">
                            <div className="flex items-center gap-3">
                                <div className="p-2 bg-green-100 dark:bg-green-900 rounded-lg">
                                    <Settings className="h-5 w-5 text-green-600 dark:text-green-300" />
                                </div>
                                <SectionTitle>تنظیمات تخفیف</SectionTitle>
                            </div>
                        </div>
                        <div className="p-6">
                            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                                <div className="space-y-2">
                                    <Label>نوع تخفیف</Label>
                                    <select
                                        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"
                                        {...register('type')}
                                        data-testid="discount-type-select"
                                    >
                                        <option value="percentage">درصدی</option>
                                        <option value="fixed">مبلغ ثابت</option>
                                        <option value="fee_percentage">درصد کارمزد</option>
                                    </select>
                                    {errors.type && <p className="text-sm text-red-600 dark:text-red-400">{errors.type.message as string}</p>}
                                </div>
                                <Input
                                    label="مقدار تخفیف"
                                    type="number"
                                    step="0.01"
                                    placeholder="حداکثر ۹۹۹,۹۹۹"
                                    error={errors.value?.message as string}
                                    thousandSeparator
                                    numeric
                                    {...register('value')}
                                    data-testid="discount-value-input"
                                />
                                <div className="space-y-2">
                                    <Label>وضعیت</Label>
                                    <select
                                        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"
                                        {...register('status')}
                                        data-testid="discount-status-select"
                                        required
                                        aria-required="true"
                                    >
                                        <option value="active">فعال</option>
                                        <option value="inactive">غیرفعال</option>
                                    </select>
                                    {errors.status && <p className="text-sm text-red-600 dark:text-red-400" role="alert">{errors.status.message as string}</p>}
                                </div>
                                <div className="lg:col-span-3">
                                    <Label className="text-base font-semibold text-gray-800 dark:text-gray-200 mb-4 block">سطح اعمال تخفیف</Label>
                                    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                                        {[
                                            {
                                                value: 'invoice',
                                                label: 'کل سبد خرید',
                                                description: 'تخفیف روی کل مبلغ سبد خرید',
                                                icon: '🛒',
                                                color: 'blue'
                                            },
                                            {
                                                value: 'category',
                                                label: 'دسته‌بندی خاص',
                                                description: 'تخفیف روی محصولات دسته‌بندی‌های خاص',
                                                icon: '📁',
                                                color: 'green'
                                            },
                                            {
                                                value: 'product',
                                                label: 'محصول خاص',
                                                description: 'تخفیف روی محصولات خاص',
                                                icon: '📦',
                                                color: 'purple'
                                            },
                                            {
                                                value: 'shipping',
                                                label: 'هزینه ارسال',
                                                description: 'تخفیف روی هزینه ارسال',
                                                icon: '🚚',
                                                color: 'orange'
                                            },
                                            {
                                                value: 'product_fee',
                                                label: 'کارمزد محصول',
                                                description: 'تخفیف روی کارمزد محصول',
                                                icon: '💰',
                                                color: 'red'
                                            }
                                        ].map(option => {
                                            const isSelected = selectedApplicationLevel === option.value;

                                            const getColorClasses = (color: string, selected: boolean) => {
                                                const baseClasses = 'relative flex flex-col p-4 border-2 rounded-xl cursor-pointer transition-all duration-200 hover:shadow-lg transform hover:-translate-y-1';

                                                if (selected) {
                                                    switch (color) {
                                                        case 'blue':
                                                            return `${baseClasses} border-blue-500 bg-blue-50 dark:bg-blue-900/30 shadow-lg`;
                                                        case 'green':
                                                            return `${baseClasses} border-green-500 bg-green-50 dark:bg-green-900/30 shadow-lg`;
                                                        case 'purple':
                                                            return `${baseClasses} border-purple-500 bg-purple-50 dark:bg-purple-900/30 shadow-lg`;
                                                        case 'orange':
                                                            return `${baseClasses} border-orange-500 bg-orange-50 dark:bg-orange-900/30 shadow-lg`;
                                                        case 'red':
                                                            return `${baseClasses} border-red-500 bg-red-50 dark:bg-red-900/30 shadow-lg`;
                                                        default:
                                                            return `${baseClasses} border-gray-500 bg-gray-50 dark:bg-gray-900/30 shadow-lg`;
                                                    }
                                                } else {
                                                    return `${baseClasses} border-gray-200 dark:border-gray-600 hover:bg-gray-50 dark:hover:bg-gray-700 hover:border-gray-300 dark:hover:border-gray-500`;
                                                }
                                            };

                                            const getIndicatorClasses = (color: string, selected: boolean) => {
                                                const baseClasses = 'absolute top-3 left-3 w-5 h-5 rounded-full border-2 flex items-center justify-center transition-all';

                                                if (selected) {
                                                    switch (color) {
                                                        case 'blue':
                                                            return `${baseClasses} border-blue-500 bg-blue-500`;
                                                        case 'green':
                                                            return `${baseClasses} border-green-500 bg-green-500`;
                                                        case 'purple':
                                                            return `${baseClasses} border-purple-500 bg-purple-500`;
                                                        case 'orange':
                                                            return `${baseClasses} border-orange-500 bg-orange-500`;
                                                        case 'red':
                                                            return `${baseClasses} border-red-500 bg-red-500`;
                                                        default:
                                                            return `${baseClasses} border-gray-500 bg-gray-500`;
                                                    }
                                                } else {
                                                    return `${baseClasses} border-gray-300 dark:border-gray-600`;
                                                }
                                            };

                                            return (
                                                <label
                                                    key={option.value}
                                                    className={getColorClasses(option.color, isSelected)}
                                                >
                                                    <input
                                                        type="radio"
                                                        name="application_level"
                                                        value={option.value}
                                                        checked={isSelected}
                                                        onChange={() => handleApplicationLevelChange(option.value)}
                                                        className="sr-only"
                                                    />

                                                    {/* Selection indicator */}
                                                    <div className={getIndicatorClasses(option.color, isSelected)}>
                                                        {isSelected && (
                                                            <svg className="w-3 h-3 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M5 13l4 4L19 7"></path>
                                                            </svg>
                                                        )}
                                                    </div>

                                                    {/* Icon */}
                                                    <div className="text-2xl mb-3 mt-2 text-center">
                                                        {option.icon}
                                                    </div>

                                                    {/* Content */}
                                                    <div className="text-center">
                                                        <div className="text-sm font-semibold text-gray-900 dark:text-gray-100 mb-2">
                                                            {option.label}
                                                        </div>
                                                        <div className="text-xs text-gray-600 dark:text-gray-400 leading-relaxed">
                                                            {option.description}
                                                        </div>
                                                    </div>
                                                </label>
                                            );
                                        })}
                                    </div>
                                    {errors.application_level && <p className="text-sm text-red-600 dark:text-red-400 mt-3 font-medium" role="alert">{errors.application_level.message as string}</p>}
                                </div>

                                {/* Conditional Product Selection */}
                                {selectedApplicationLevel === 'product' && (
                                    <div className="lg:col-span-3">
                                        <div className="bg-gradient-to-r from-purple-50 to-purple-100 dark:from-purple-900/20 dark:to-purple-800/20 rounded-xl p-6 border border-purple-200 dark:border-purple-700">
                                            <div className="flex items-center gap-3 mb-4">
                                                <div className="p-2 bg-purple-100 dark:bg-purple-900 rounded-lg">
                                                    <span className="text-xl">📦</span>
                                                </div>
                                                <div>
                                                    <h3 className="text-base font-semibold text-purple-900 dark:text-purple-100">انتخاب محصولات خاص</h3>
                                                    <p className="text-sm text-purple-700 dark:text-purple-300">محصولات مورد نظر برای اعمال تخفیف را انتخاب کنید</p>
                                                </div>
                                            </div>
                                            <MultiSelectAutocomplete
                                                label=""
                                                options={productOptions}
                                                selectedValues={selectedProductIds}
                                                onChange={setSelectedProductIds}
                                                placeholder="جستجو و انتخاب محصولات..."
                                                isLoading={productsLoading && productPage === 1}
                                                disabled={false}
                                                onSearchChange={(q) => { setProductSearch(q); setProductPage(1); }}
                                                onLoadMore={() => {
                                                    if (!productsLoading && productSearchResult && ((productSearchResult.total || 0) > accumulatedProducts.length)) {
                                                        setProductPage(prev => prev + 1);
                                                    }
                                                }}
                                                hasMore={!!productSearchResult && accumulatedProducts.length < (productSearchResult.total || 0)}
                                                loadingMore={productsLoading && productPage > 1}
                                            />
                                            <div className="mt-3 p-3 bg-purple-100/50 dark:bg-purple-900/30 rounded-lg">
                                                <p className="text-sm text-purple-700 dark:text-purple-300 flex items-center gap-2">
                                                    <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                                                    </svg>
                                                    در صورت انتخاب محصولات، تخفیف فقط روی این محصولات اعمال خواهد شد.
                                                </p>
                                            </div>
                                        </div>
                                    </div>
                                )}

                                {/* Conditional Category Selection */}
                                {selectedApplicationLevel === 'category' && (
                                    <div className="lg:col-span-3">
                                        <div className="bg-gradient-to-r from-green-50 to-green-100 dark:from-green-900/20 dark:to-green-800/20 rounded-xl p-6 border border-green-200 dark:border-green-700">
                                            <div className="flex items-center gap-3 mb-4">
                                                <div className="p-2 bg-green-100 dark:bg-green-900 rounded-lg">
                                                    <span className="text-xl">📁</span>
                                                </div>
                                                <div>
                                                    <h3 className="text-base font-semibold text-green-900 dark:text-green-100">انتخاب دسته‌بندی‌های خاص</h3>
                                                    <p className="text-sm text-green-700 dark:text-green-300">دسته‌بندی‌های مورد نظر برای اعمال تخفیف را انتخاب کنید</p>
                                                </div>
                                            </div>
                                            <MultiSelectAutocomplete
                                                label=""
                                                options={categoryOptions}
                                                selectedValues={selectedCategoryIds}
                                                onChange={setSelectedCategoryIds}
                                                placeholder="جستجو و انتخاب دسته‌بندی‌ها..."
                                                isLoading={categoriesLoading && categoryPage === 1}
                                                disabled={false}
                                                onSearchChange={(q) => { setCategorySearch(q); setCategoryPage(1); }}
                                                onLoadMore={() => {
                                                    if (!categoriesLoading && categorySearchResult && (categorySearchResult.length > 0)) {
                                                        setCategoryPage(prev => prev + 1);
                                                    }
                                                }}
                                                hasMore={!!categorySearchResult && categorySearchResult.length >= CATEGORIES_PAGE_SIZE}
                                                loadingMore={categoriesLoading && categoryPage > 1}
                                            />
                                            <div className="mt-3 p-3 bg-green-100/50 dark:bg-green-900/30 rounded-lg">
                                                <p className="text-sm text-green-700 dark:text-green-300 flex items-center gap-2">
                                                    <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                                                    </svg>
                                                    در صورت انتخاب دسته‌بندی‌ها، تخفیف فقط روی محصولات این دسته‌ها اعمال خواهد شد.
                                                </p>
                                            </div>
                                        </div>
                                    </div>
                                )}

                                <Input
                                    label="حداقل مبلغ خرید"
                                    type="number"
                                    step="0.01"
                                    placeholder="حداکثر ۹۹,۹۹۹,۹۹۹"
                                    error={errors.min_purchase_amount?.message as string}
                                    thousandSeparator
                                    numeric
                                    {...register('min_purchase_amount')}
                                />
                                <Input
                                    label="حداکثر مبلغ تخفیف"
                                    type="number"
                                    step="0.01"
                                    placeholder="حداکثر ۹۹,۹۹۹,۹۹۹"
                                    error={errors.max_discount_amount?.message as string}
                                    thousandSeparator
                                    numeric
                                    {...register('max_discount_amount')}
                                />
                            </div>

                            <div className="mt-6 grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                                <Input
                                    label="حداکثر تعداد استفاده"
                                    type="number"
                                    placeholder="حداکثر ۹۹۹,۹۹۹"
                                    error={errors.usage_limit?.message as string}
                                    {...register('usage_limit')}
                                />
                                <Input
                                    label="حداکثر استفاده هر کاربر"
                                    type="number"
                                    placeholder="حداکثر ۹۹,۹۹۹"
                                    error={errors.user_usage_limit?.message as string}
                                    {...register('user_usage_limit')}
                                />
                                <div className="flex items-center gap-3 mt-8">
                                    <input
                                        id="single_use"
                                        type="checkbox"
                                        className="h-5 w-5 text-blue-600 border-2 border-gray-300 rounded focus:ring-blue-500 focus:ring-2"
                                        {...register('single_use')}
                                    />
                                    <Label htmlFor="single_use" className="text-base">تک‌بار مصرف</Label>
                                </div>
                            </div>
                        </div>
                    </div>

                    {/* بازه زمانی */}
                    <div className="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 overflow-hidden">
                        <div className="bg-gradient-to-r from-purple-50 to-pink-50 dark:from-gray-700 dark:to-gray-600 px-6 py-4 border-b border-gray-200 dark:border-gray-700">
                            <div className="flex items-center gap-3">
                                <div className="p-2 bg-purple-100 dark:bg-purple-900 rounded-lg">
                                    <Calendar className="h-5 w-5 text-purple-600 dark:text-purple-300" />
                                </div>
                                <SectionTitle>بازه زمانی اعتبار</SectionTitle>
                            </div>
                        </div>
                        <div className="p-6">
                            <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                                <Controller
                                    name="valid_from"
                                    control={control}
                                    render={({ field }) => (
                                        <JalaliDateTimePicker
                                            label="شروع اعتبار"
                                            value={field.value}
                                            onChange={field.onChange}
                                            error={errors.valid_from?.message as string}
                                        />
                                    )}
                                />
                                <Controller
                                    name="valid_to"
                                    control={control}
                                    render={({ field }) => (
                                        <JalaliDateTimePicker
                                            label="پایان اعتبار"
                                            value={field.value}
                                            onChange={field.onChange}
                                            error={errors.valid_to?.message as string}
                                        />
                                    )}
                                />
                            </div>
                        </div>
                    </div>

                    {/* محدودیت‌های کاربری */}
                    <div className="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 overflow-visible">
                        <div className="bg-gradient-to-r from-orange-50 to-red-50 dark:from-gray-700 dark:to-gray-600 px-6 py-4 border-b border-gray-200 dark:border-gray-700">
                            <div className="flex items-center gap-3">
                                <div className="p-2 bg-orange-100 dark:bg-orange-900 rounded-lg">
                                    <Users className="h-5 w-5 text-orange-600 dark:text-orange-300" />
                                </div>
                                <SectionTitle>محدودیت‌های کاربری</SectionTitle>
                            </div>
                        </div>
                        <div className="p-6">
                            <div className="space-y-6">
                                <div className="grid grid-cols-1 gap-6">
                                    <div className="space-y-2">
                                        <Label>گروه کاربری</Label>
                                        <select
                                            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"
                                            {...register('user_restrictions.user_group')}
                                        >
                                            <option value="loyal">وفادار (loyal)</option>
                                            <option value="new">کاربر جدید (new)</option>
                                            <option value="all">همه کاربران (all)</option>
                                        </select>
                                    </div>
                                </div>

                                {/* User Selection */}
                                <div className="border-t border-gray-200 dark:border-gray-700 pt-6">
                                    <SingleSelectAutocomplete
                                        label="انتخاب کاربر خاص"
                                        options={userOptions}
                                        selectedValue={selectedUserId}
                                        onChange={setSelectedUserId}
                                        placeholder="جستجو و انتخاب کاربر..."
                                        isLoading={usersLoading && userOffset === 0}
                                        disabled={false}
                                        onSearchChange={(q) => { setUserSearch(q); setUserOffset(0); }}
                                        onLoadMore={() => {
                                            if (!usersLoading && searchResult && (searchResult.total > accumulatedUsers.length)) {
                                                setUserOffset(prev => prev + USERS_PAGE_SIZE);
                                            }
                                        }}
                                        hasMore={!!searchResult && accumulatedUsers.length < (searchResult.total || 0)}
                                        loadingMore={usersLoading && userOffset > 0}
                                    />
                                    <p className="text-sm text-gray-500 dark:text-gray-400 mt-2">
                                        در صورت انتخاب کاربر، کد تخفیف فقط برای آن کاربر قابل استفاده خواهد بود.
                                    </p>
                                </div>
                            </div>
                        </div>
                    </div>

                    {/* اطلاعات تکمیلی */}
                    <div className="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 overflow-hidden">
                        <div className="bg-gradient-to-r from-teal-50 to-cyan-50 dark:from-gray-700 dark:to-gray-600 px-6 py-4 border-b border-gray-200 dark:border-gray-700">
                            <div className="flex items-center gap-3">
                                <div className="p-2 bg-teal-100 dark:bg-teal-900 rounded-lg">
                                    <Info className="h-5 w-5 text-teal-600 dark:text-teal-300" />
                                </div>
                                <SectionTitle>اطلاعات تکمیلی</SectionTitle>
                            </div>
                        </div>
                        <div className="p-6">
                            <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                                <Input
                                    label="نام کمپین"
                                    type="text"
                                    placeholder="مثال: summer_sale"
                                    {...register('meta.campaign')}
                                />
                                <Input
                                    label="دسته‌بندی کمپین"
                                    type="text"
                                    placeholder="مثال: seasonal"
                                    {...register('meta.category')}
                                />
                            </div>
                        </div>
                    </div>

                    {/* دکمه‌های اکشن */}
                    <div className="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 p-6">
                        <div className="flex flex-col sm:flex-row gap-3 justify-end">
                            <Button
                                type="button"
                                variant="secondary"
                                onClick={() => navigate('/discount-codes')}
                                className="sm:order-1"
                                data-testid="cancel-discount-button"
                            >
                                انصراف
                            </Button>
                            <Button
                                type="submit"
                                variant="primary"
                                loading={isLoading}
                                disabled={!isValid}
                                className="sm:order-2 bg-gradient-to-r from-blue-600 to-blue-700 hover:from-blue-700 hover:to-blue-800"
                                data-testid="submit-discount-button"
                            >
                                {isEdit ? 'به‌روزرسانی کد تخفیف' : 'ایجاد کد تخفیف'}
                            </Button>
                        </div>
                    </div>
                </form>
            </div>
        </PageContainer>
    );
};

export default DiscountCodeFormPage;



