'use client';

import { useState, useCallback, useMemo } from 'react';
import { useRouter } from 'next/navigation';
import toast from 'react-hot-toast';
import Select, { StylesConfig, MultiValue } from 'react-select';
import AsyncSelect from 'react-select/async';
import { getApiErrorMessage } from '@/lib/utils/apiError';

// ─── Types ────────────────────────────────────────────────────────────────
interface Category {
  id: string;
  name: string;
  parent_id: string | null;
}

interface Product {
  id: string;
  name: string;
  sku: string;
  category_id: string | null;
}

interface User {
  id: string;
  name: string;
  email: string;
}

interface Language {
  code: string;
  name: string;
  name_native?: string;
  is_default?: boolean;
  is_active?: boolean;
}

interface ApplicableItem {
  applicable_type: 'all' | 'category' | 'product';
  applicable_id: string | null;
}

interface CouponTranslation {
  language_code: string;
  offer_title?: string | null;
  offer_badge?: string | null;
  offer_description?: string | null;
}

interface CouponAssignment {
  user_id: string;
  usage_limit: number;
  user_name?: string;
  user_email?: string;
}

interface CouponData {
  id?: string;
  code: string;
  name: string;
  description: string | null;
  type: 'percentage' | 'fixed';
  value: number;
  min_order_amount: number;
  max_discount: number | null;
  usage_limit: number | null;
  usage_limit_per_user: number;
  valid_from: string;
  valid_until: string;
  assignment_type: 'public' | 'manual';
  is_active: boolean;
  is_offer?: boolean;
  is_featured?: boolean;
  applicable_items: ApplicableItem[];
  assignments?: CouponAssignment[];
  translations?: CouponTranslation[];
}

interface CouponFormProps {
  mode: 'create' | 'edit';
  initialData?: CouponData | null;
  categories: Category[];
  products: Product[];
  languages?: Language[];
}

interface SelectOption {
  value: string;
  label: string;
}

// ─── Styles ───────────────────────────────────────────────────────────────
const INPUT_STYLE = {
  background: 'var(--color-surface-alt)',
  border: '1px solid var(--color-border)',
  color: 'var(--color-text)',
} as const;

const LABEL_STYLE = { color: 'var(--color-text-secondary)' } as const;

const selectStyles: StylesConfig<SelectOption, true> = {
  control: (base, state) => ({
    ...base,
    background: 'var(--color-surface-alt)',
    border: `1px solid ${state.isFocused ? 'var(--color-cta)' : 'var(--color-border)'}`,
    borderRadius: '0.5rem',
    boxShadow: state.isFocused
      ? '0 0 0 2px color-mix(in srgb, var(--color-cta) 20%, transparent)'
      : 'none',
    minHeight: '42px',
    cursor: 'pointer',
    transition: 'all 0.15s',
    '&:hover': { borderColor: 'var(--color-cta)' },
  }),
  valueContainer: (base) => ({ ...base, padding: '2px 8px' }),
  multiValue: (base) => ({
    ...base,
    background: 'var(--color-cta-light)',
    borderRadius: '0.375rem',
    margin: '2px',
  }),
  multiValueLabel: (base) => ({
    ...base,
    color: 'var(--color-cta)',
    fontSize: '0.813rem',
    padding: '2px 6px',
  }),
  multiValueRemove: (base) => ({
    ...base,
    color: 'var(--color-cta)',
    borderRadius: '0 0.375rem 0.375rem 0',
    cursor: 'pointer',
    '&:hover': { background: 'var(--color-danger)', color: 'white' },
  }),
  input: (base) => ({ ...base, color: 'var(--color-text)', fontSize: '0.875rem' }),
  placeholder: (base) => ({
    ...base,
    color: 'var(--color-text-tertiary)',
    fontSize: '0.875rem',
  }),
  menu: (base) => ({
    ...base,
    background: 'var(--color-surface)',
    border: '1px solid var(--color-border)',
    borderRadius: '0.5rem',
    boxShadow: 'var(--shadow-card-md)',
    zIndex: 50,
    overflow: 'hidden',
  }),
  menuList: (base) => ({ ...base, padding: '4px' }),
  option: (base, state) => ({
    ...base,
    background: state.isSelected
      ? 'var(--color-cta)'
      : state.isFocused
        ? 'color-mix(in srgb, var(--color-cta) 10%, transparent)'
        : 'transparent',
    color: state.isSelected ? 'white' : 'var(--color-text)',
    fontSize: '0.875rem',
    borderRadius: '0.375rem',
    cursor: 'pointer',
    padding: '8px 12px',
    '&:active': { background: 'color-mix(in srgb, var(--color-cta) 20%, transparent)' },
  }),
  noOptionsMessage: (base) => ({
    ...base,
    color: 'var(--color-text-secondary)',
    fontSize: '0.875rem',
  }),
};

// ─── User Search ───────────────────────────────────────────────────────────
async function searchUsers(inputValue: string): Promise<SelectOption[]> {
  if (!inputValue || inputValue.length < 2) return [];
  try {
    const res = await fetch(`/api/coupons/items/users?search=${encodeURIComponent(inputValue)}`);
    if (!res.ok) return [];
    const data = await res.json();
    return (data.data || []).map((user: User) => ({
      value: user.id,
      label: `${user.name} (${user.email})`,
    }));
  } catch {
    return [];
  }
}

// ─── Component ────────────────────────────────────────────────────────────
export default function CouponForm({
  mode,
  initialData,
  categories,
  products,
  languages = [],
}: CouponFormProps) {
  const router = useRouter();
  const isEditing = mode === 'edit';

  // ── Helpers ──────────────────────────────────────────────────────────
  /**
   * ✅ FIX: GET /api/coupons/[id] ab already admin ke site-timezone mein
   * "naive" local datetime string bhejta hai (e.g. "2026-06-29T13:00:00"),
   * koi `Z` suffix nahi hota. Isliye yahan `new Date(...).toISOString()`
   * se dobara convert karne ki ZAROORAT NAHI — usay wapis UTC bana kar
   * browser ke apne timezone se guzaarna hi double-conversion bug
   * (5-ghante-ka-farq) ki wajah thi. Ab bas string ko <input type=
   * "datetime-local"> ke required "YYYY-MM-DDTHH:mm" format tak trim
   * karte hain — koi timezone math nahi.
   */
  const formatDateForInput = (dateStr: string) => {
    if (!dateStr) return '';
    return dateStr.slice(0, 16);
  };

  /**
   * Naya coupon banate waqt default value — browser ka apna current
   * local time, "datetime-local" input ke format mein.
   */
  const getCurrentDateTime = () => {
    const now = new Date();
    const pad = (n: number) => String(n).padStart(2, '0');
    return `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}T${pad(now.getHours())}:${pad(now.getMinutes())}`;
  };

  const getInitialApplicableType = (): 'all' | 'category' | 'product' => {
    if (!initialData?.applicable_items || initialData.applicable_items.length === 0)
      return 'all';
    const firstType = initialData.applicable_items[0].applicable_type;
    if (firstType === 'all') return 'all';
    if (firstType === 'category') return 'category';
    return 'product';
  };

  // ── Options ───────────────────────────────────────────────────────────
  const categoryOptions: SelectOption[] = useMemo(() => {
    return categories.map((cat) => ({ value: cat.id, label: cat.name }));
  }, [categories]);

  const productOptions: SelectOption[] = useMemo(() => {
    return products.map((prod) => ({
      value: prod.id,
      label: `${prod.name} (${prod.sku})`,
    }));
  }, [products]);

  const activeLanguages = useMemo(() => {
    if (languages.length === 0) return [{ code: 'en', name: 'English', is_default: true }];
    return languages
      .filter((l) => l.is_active !== false)
      .sort((a, b) => {
        if (a.is_default) return -1;
        if (b.is_default) return 1;
        return (a.name || '').localeCompare(b.name || '');
      });
  }, [languages]);

  const isMultiLang = activeLanguages.length > 1;

  // ── Initial Values ────────────────────────────────────────────────────
  const initialTranslations: CouponTranslation[] = useMemo(() => {
    if (initialData?.translations && initialData.translations.length > 0) {
      return initialData.translations;
    }
    return activeLanguages.map((lang) => ({
      language_code: lang.code,
      offer_title: '',
      offer_badge: '',
      offer_description: '',
    }));
  }, [initialData, activeLanguages]);

  const initialSelectedCategories = useMemo(() => {
    if (!initialData?.applicable_items) return [];
    const catIds = initialData.applicable_items
      .filter((item) => item.applicable_type === 'category' && item.applicable_id)
      .map((item) => item.applicable_id!);
    return categoryOptions.filter((opt) => catIds.includes(opt.value));
  }, [initialData, categoryOptions]);

  const initialSelectedProducts = useMemo(() => {
    if (!initialData?.applicable_items) return [];
    const prodIds = initialData.applicable_items
      .filter((item) => item.applicable_type === 'product' && item.applicable_id)
      .map((item) => item.applicable_id!);
    return productOptions.filter((opt) => prodIds.includes(opt.value));
  }, [initialData, productOptions]);

  const initialSelectedUsers = useMemo(() => {
    if (!initialData?.assignments || initialData.assignments.length === 0) return [];
    return initialData.assignments.map((a) => ({
      value: a.user_id,
      label:
        a.user_name && a.user_email
          ? `${a.user_name} (${a.user_email})`
          : a.user_id,
    }));
  }, [initialData]);

  const initialUserLimits = useMemo(() => {
    if (!initialData?.assignments) return {};
    const limits: Record<string, number> = {};
    initialData.assignments.forEach((a) => {
      limits[a.user_id] = a.usage_limit || 1;
    });
    return limits;
  }, [initialData]);

  // ── Form State ────────────────────────────────────────────────────────
  const [formData, setFormData] = useState({
    code: initialData?.code || '',
    name: initialData?.name || '',
    description: initialData?.description || '',
    type: (initialData?.type || 'percentage') as 'percentage' | 'fixed',
    value: initialData?.value || 0,
    min_order_amount: initialData?.min_order_amount || 0,
    max_discount: (initialData?.max_discount || null) as number | null,
    usage_limit: (initialData?.usage_limit || null) as number | null,
    usage_limit_per_user: initialData?.usage_limit_per_user || 1,
    valid_from: initialData?.valid_from
      ? formatDateForInput(initialData.valid_from)
      : getCurrentDateTime(),
    valid_until: initialData?.valid_until
      ? formatDateForInput(initialData.valid_until)
      : '',
    assignment_type: (initialData?.assignment_type || 'public') as 'public' | 'manual',
    is_active: initialData?.is_active !== undefined ? initialData.is_active : true,
    is_offer: initialData?.is_offer || false,
    is_featured: initialData?.is_featured || false,
  });

  const [translations, setTranslations] = useState<CouponTranslation[]>(initialTranslations);
  const [activeLangTab, setActiveLangTab] = useState<string>(activeLanguages[0]?.code || 'en');
  const [applicableType, setApplicableType] = useState<'all' | 'category' | 'product'>(
    getInitialApplicableType(),
  );
  const [selectedCategories, setSelectedCategories] =
    useState<MultiValue<SelectOption>>(initialSelectedCategories);
  const [selectedProducts, setSelectedProducts] =
    useState<MultiValue<SelectOption>>(initialSelectedProducts);
  const [selectedUsers, setSelectedUsers] =
    useState<MultiValue<SelectOption>>(initialSelectedUsers);
  const [userUsageLimits, setUserUsageLimits] = useState<Record<string, number>>(initialUserLimits);
  const [defaultUserLimit, setDefaultUserLimit] = useState(1);
  const [loading, setLoading] = useState(false);
  const [errors, setErrors] = useState<Record<string, string>>({});

  // ── Handlers ──────────────────────────────────────────────────────────
  const handleChange = useCallback(
    (field: string, value: unknown) => {
      setFormData((prev) => ({ ...prev, [field]: value }));
      if (errors[field]) {
        setErrors((prev) => {
          const next = { ...prev };
          delete next[field];
          return next;
        });
      }
    },
    [errors],
  );

  const handleToggle = useCallback((field: keyof typeof formData) => {
    setFormData((prev) => ({ ...prev, [field]: !prev[field] }));
  }, []);

  const handleApplicableTypeChange = useCallback(
    (type: 'all' | 'category' | 'product') => {
      setApplicableType(type);
      setSelectedCategories([]);
      setSelectedProducts([]);
    },
    [],
  );

  const handleTranslationChange = useCallback(
    (langCode: string, field: string, value: string) => {
      setTranslations((prev) => {
        const existing = prev.find((t) => t.language_code === langCode);
        if (existing) {
          return prev.map((t) =>
            t.language_code === langCode ? { ...t, [field]: value } : t,
          );
        }
        return [...prev, { language_code: langCode, [field]: value }];
      });
    },
    [],
  );

  const getTranslation = useCallback(
    (langCode: string): CouponTranslation => {
      return (
        translations.find((t) => t.language_code === langCode) || {
          language_code: langCode,
          offer_title: '',
          offer_badge: '',
          offer_description: '',
        }
      );
    },
    [translations],
  );

  const handleUsersChange = useCallback(
    (newValue: MultiValue<SelectOption>) => {
      setSelectedUsers(newValue);
      const newLimits: Record<string, number> = {};
      newValue.forEach((user) => {
        newLimits[user.value] = userUsageLimits[user.value] || defaultUserLimit;
      });
      setUserUsageLimits(newLimits);
    },
    [userUsageLimits, defaultUserLimit],
  );

  const handleUserLimitChange = useCallback((userId: string, limit: number) => {
    setUserUsageLimits((prev) => ({ ...prev, [userId]: limit }));
  }, []);

  // ── Build Functions ───────────────────────────────────────────────────
  const buildApplicableItems = useCallback((): ApplicableItem[] => {
    if (applicableType === 'all')
      return [{ applicable_type: 'all', applicable_id: null }];
    if (applicableType === 'category') {
      return selectedCategories.map((cat) => ({
        applicable_type: 'category' as const,
        applicable_id: cat.value,
      }));
    }
    return selectedProducts.map((prod) => ({
      applicable_type: 'product' as const,
      applicable_id: prod.value,
    }));
  }, [applicableType, selectedCategories, selectedProducts]);

  const buildAssignments = useCallback((): CouponAssignment[] => {
    return selectedUsers.map((user) => ({
      user_id: user.value,
      usage_limit: userUsageLimits[user.value] || 1,
    }));
  }, [selectedUsers, userUsageLimits]);

  // ── Submit ────────────────────────────────────────────────────────────
  const handleSubmit = useCallback(
    async (e: React.FormEvent) => {
      e.preventDefault();
      setErrors({});
      setLoading(true);

      const newErrors: Record<string, string> = {};
      if (!formData.code.trim()) newErrors.code = 'Code is required';
      if (!formData.name.trim()) newErrors.name = 'Name is required';
      if (formData.value <= 0) newErrors.value = 'Value must be greater than 0';
      if (formData.type === 'percentage' && formData.value > 100)
        newErrors.value = 'Percentage cannot exceed 100';
      if (!formData.valid_from) newErrors.valid_from = 'Start date is required';
      if (!formData.valid_until) newErrors.valid_until = 'End date is required';
      if (
        formData.valid_from &&
        formData.valid_until &&
        // ✅ Naive strings ka lexical comparison bhi chronological order ke
        // liye kaafi hai kyunke format hamesha "YYYY-MM-DDTHH:mm" hai —
        // koi Date parsing/timezone ki zaroorat nahi is check ke liye.
        formData.valid_from >= formData.valid_until
      ) {
        newErrors.valid_until = 'End date must be after start date';
      }
      if (
        applicableType !== 'all' &&
        applicableType === 'category' &&
        selectedCategories.length === 0
      ) {
        newErrors.applicable = 'Select at least one category';
      }
      if (
        applicableType !== 'all' &&
        applicableType === 'product' &&
        selectedProducts.length === 0
      ) {
        newErrors.applicable = 'Select at least one product';
      }
      if (formData.assignment_type === 'manual' && selectedUsers.length === 0) {
        newErrors.users = 'Select at least one user for manual assignment';
      }

      if (Object.keys(newErrors).length > 0) {
        setErrors(newErrors);
        toast.error('Please fix the validation errors');
        setLoading(false);
        return;
      }

      try {
        const applicableItems = buildApplicableItems();
        const assignments =
          formData.assignment_type === 'manual' ? buildAssignments() : [];
        const validTranslations = translations.filter(
          (t) => t.offer_title?.trim() || t.offer_badge?.trim(),
        );

        const url = isEditing
          ? `/api/coupons/${initialData?.id}`
          : '/api/coupons';
        const method = isEditing ? 'PUT' : 'POST';

        const payload = {
          ...formData,
          code: formData.code.toUpperCase(),
          // ✅ FIX: date conversion hata di — dono ab naive local datetime
          // strings hain (e.g. "2026-06-29T13:00") jo admin ne exactly
          // waisi hi type ki hain. Backend (localToUTC + getSiteTimezone)
          // inhe khud site-timezone ke hisaab se UTC mein convert karega.
          // Yahan se koi bhi Date()/toISOString() call hatana zaroori tha,
          // warna browser apne timezone se pehle UTC bana deta tha aur
          // backend usay dobara convert kar deta tha — isi se 5-ghante
          // ka farq aa raha tha.
          valid_from: formData.valid_from,
          valid_until: formData.valid_until,
          applicable_items: applicableItems,
          assignments: assignments,
          translations: validTranslations,
        };

        const res = await fetch(url, {
          method,
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(payload),
        });

        const data = await res.json();

        if (!res.ok || !data.success) {
          toast.error(getApiErrorMessage(data, 'Failed to save coupon'));
          return;
        }

        toast.success(
          data.message ||
            (isEditing ? 'Coupon updated successfully' : 'Coupon created successfully'),
        );
        router.push('/admin/dashboard/coupons');
        router.refresh();
      } catch (err) {
        console.error('[CouponForm]', err);
        toast.error('Network error — please try again');
      } finally {
        setLoading(false);
      }
    },
    [
      formData,
      applicableType,
      selectedCategories,
      selectedProducts,
      selectedUsers,
      translations,
      buildApplicableItems,
      buildAssignments,
      isEditing,
      initialData,
      router,
    ],
  );

  const loadOptions = useCallback(
    (inputValue: string) => searchUsers(inputValue),
    [],
  );

  // ── Render ────────────────────────────────────────────────────────────
  return (
    <div
      className="p-6 md:p-8"
      style={{
        background: 'var(--color-surface)',
        border: '1px solid var(--color-border)',
        borderRadius: 'var(--radius-card)',
        boxShadow: 'var(--shadow-card-md)',
        maxWidth: '900px',
        width: '100%',
      }}
    >
      <form onSubmit={handleSubmit}>
        <div className="space-y-6">
          {/* ── Basic Info ──────────────────────────────────────────── */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium mb-1.5" style={LABEL_STYLE}>
                Coupon Code <span className="text-red-500">*</span>
              </label>
              <input
                type="text"
                value={formData.code}
                onChange={(e) => handleChange('code', e.target.value.toUpperCase())}
                placeholder="e.g., SALE50"
                maxLength={50}
                className="w-full px-4 py-2.5 rounded-lg text-sm font-mono uppercase outline-none transition-all focus:ring-2 focus:ring-cta/20"
                style={{
                  ...INPUT_STYLE,
                  border: errors.code
                    ? '1px solid var(--color-danger)'
                    : INPUT_STYLE.border,
                }}
              />
              {errors.code && (
                <p className="text-xs mt-1" style={{ color: 'var(--color-danger)' }}>
                  {errors.code}
                </p>
              )}
            </div>

            <div>
              <label className="block text-sm font-medium mb-1.5" style={LABEL_STYLE}>
                Name <span className="text-red-500">*</span>
              </label>
              <input
                type="text"
                value={formData.name}
                onChange={(e) => handleChange('name', e.target.value)}
                placeholder="e.g., Summer Sale 50% Off"
                maxLength={100}
                className="w-full px-4 py-2.5 rounded-lg text-sm outline-none transition-all focus:ring-2 focus:ring-cta/20"
                style={{
                  ...INPUT_STYLE,
                  border: errors.name
                    ? '1px solid var(--color-danger)'
                    : INPUT_STYLE.border,
                }}
              />
              {errors.name && (
                <p className="text-xs mt-1" style={{ color: 'var(--color-danger)' }}>
                  {errors.name}
                </p>
              )}
            </div>
          </div>

          {/* ── Description ─────────────────────────────────────────── */}
          <div>
            <label className="block text-sm font-medium mb-1.5" style={LABEL_STYLE}>
              Description
            </label>
            <textarea
              rows={2}
              value={formData.description}
              onChange={(e) => handleChange('description', e.target.value)}
              placeholder="Optional description for internal use"
              className="w-full px-4 py-2.5 rounded-lg text-sm outline-none transition-all focus:ring-2 focus:ring-cta/20 resize-none"
              style={INPUT_STYLE}
            />
          </div>

          {/* ── Discount Type & Value ────────────────────────────────── */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium mb-1.5" style={LABEL_STYLE}>
                Discount Type
              </label>
              <select
                value={formData.type}
                onChange={(e) => handleChange('type', e.target.value)}
                className="w-full px-4 py-2.5 rounded-lg text-sm outline-none transition-all focus:ring-2 focus:ring-cta/20 cursor-pointer"
                style={INPUT_STYLE}
              >
                <option value="percentage">Percentage (%)</option>
                <option value="fixed">Fixed Amount</option>
              </select>
            </div>

            <div>
              <label className="block text-sm font-medium mb-1.5" style={LABEL_STYLE}>
                Value <span className="text-red-500">*</span>
              </label>
              <input
                type="number"
                value={formData.value}
                onChange={(e) => handleChange('value', parseFloat(e.target.value) || 0)}
                min="0"
                step="0.01"
                placeholder={
                  formData.type === 'percentage' ? 'e.g., 10 for 10%' : 'e.g., 500.00'
                }
                className="w-full px-4 py-2.5 rounded-lg text-sm outline-none transition-all focus:ring-2 focus:ring-cta/20"
                style={{
                  ...INPUT_STYLE,
                  border: errors.value
                    ? '1px solid var(--color-danger)'
                    : INPUT_STYLE.border,
                }}
              />
              {errors.value && (
                <p className="text-xs mt-1" style={{ color: 'var(--color-danger)' }}>
                  {errors.value}
                </p>
              )}
            </div>
          </div>

          {/* ── Min Order & Max Discount ─────────────────────────────── */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium mb-1.5" style={LABEL_STYLE}>
                Minimum Order Amount
              </label>
              <input
                type="number"
                value={formData.min_order_amount}
                onChange={(e) =>
                  handleChange('min_order_amount', parseFloat(e.target.value) || 0)
                }
                min="0"
                step="0.01"
                className="w-full px-4 py-2.5 rounded-lg text-sm outline-none transition-all focus:ring-2 focus:ring-cta/20"
                style={INPUT_STYLE}
              />
            </div>

            {formData.type === 'percentage' && (
              <div>
                <label className="block text-sm font-medium mb-1.5" style={LABEL_STYLE}>
                  Maximum Discount Cap
                </label>
                <input
                  type="number"
                  value={formData.max_discount || ''}
                  onChange={(e) =>
                    handleChange(
                      'max_discount',
                      e.target.value ? parseFloat(e.target.value) : null,
                    )
                  }
                  min="0"
                  step="0.01"
                  placeholder="e.g., 500.00 (optional)"
                  className="w-full px-4 py-2.5 rounded-lg text-sm outline-none transition-all focus:ring-2 focus:ring-cta/20"
                  style={INPUT_STYLE}
                />
              </div>
            )}
          </div>

          {/* ── Usage Limits ─────────────────────────────────────────── */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium mb-1.5" style={LABEL_STYLE}>
                Total Usage Limit
              </label>
              <input
                type="number"
                value={formData.usage_limit || ''}
                onChange={(e) =>
                  handleChange(
                    'usage_limit',
                    e.target.value ? parseInt(e.target.value) : null,
                  )
                }
                min="1"
                placeholder="Leave empty for unlimited"
                className="w-full px-4 py-2.5 rounded-lg text-sm outline-none transition-all focus:ring-2 focus:ring-cta/20"
                style={INPUT_STYLE}
              />
            </div>

            <div>
              <label className="block text-sm font-medium mb-1.5" style={LABEL_STYLE}>
                Usage Per User
              </label>
              <input
                type="number"
                value={formData.usage_limit_per_user}
                onChange={(e) =>
                  handleChange('usage_limit_per_user', parseInt(e.target.value) || 1)
                }
                min="1"
                className="w-full px-4 py-2.5 rounded-lg text-sm outline-none transition-all focus:ring-2 focus:ring-cta/20"
                style={INPUT_STYLE}
              />
            </div>
          </div>

          {/* ── Validity Dates ───────────────────────────────────────── */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium mb-1.5" style={LABEL_STYLE}>
                Valid From <span className="text-red-500">*</span>
              </label>
              <input
                type="datetime-local"
                value={formData.valid_from}
                onChange={(e) => handleChange('valid_from', e.target.value)}
                className="w-full px-4 py-2.5 rounded-lg text-sm outline-none transition-all focus:ring-2 focus:ring-cta/20"
                style={{
                  ...INPUT_STYLE,
                  border: errors.valid_from
                    ? '1px solid var(--color-danger)'
                    : INPUT_STYLE.border,
                }}
              />
              {errors.valid_from && (
                <p className="text-xs mt-1" style={{ color: 'var(--color-danger)' }}>
                  {errors.valid_from}
                </p>
              )}
            </div>

            <div>
              <label className="block text-sm font-medium mb-1.5" style={LABEL_STYLE}>
                Valid Until <span className="text-red-500">*</span>
              </label>
              <input
                type="datetime-local"
                value={formData.valid_until}
                onChange={(e) => handleChange('valid_until', e.target.value)}
                className="w-full px-4 py-2.5 rounded-lg text-sm outline-none transition-all focus:ring-2 focus:ring-cta/20"
                style={{
                  ...INPUT_STYLE,
                  border: errors.valid_until
                    ? '1px solid var(--color-danger)'
                    : INPUT_STYLE.border,
                }}
              />
              {errors.valid_until && (
                <p className="text-xs mt-1" style={{ color: 'var(--color-danger)' }}>
                  {errors.valid_until}
                </p>
              )}
            </div>
          </div>

          {/* ── Assignment Type ──────────────────────────────────────── */}
          <div>
            <label className="block text-sm font-medium mb-2" style={LABEL_STYLE}>
              Assignment Type
            </label>
            <div className="flex flex-wrap gap-2">
              {(['public', 'manual'] as const).map((type) => (
                <button
                  key={`assign-${type}`}
                  type="button"
                  onClick={() => handleChange('assignment_type', type)}
                  className="px-4 py-2 rounded-lg text-sm font-medium transition-all capitalize"
                  style={{
                    background:
                      formData.assignment_type === type
                        ? 'var(--color-cta)'
                        : 'var(--color-surface-alt)',
                    color:
                      formData.assignment_type === type
                        ? 'white'
                        : 'var(--color-text-secondary)',
                    border:
                      formData.assignment_type === type
                        ? 'none'
                        : '1px solid var(--color-border)',
                  }}
                >
                  {type === 'public' ? '🌐 Public' : '👤 Manual'}
                </button>
              ))}
            </div>
          </div>

          {/* ── Manual User Assignment ───────────────────────────────── */}
          {formData.assignment_type === 'manual' && (
            <div>
              <label className="block text-sm font-medium mb-2" style={LABEL_STYLE}>
                Assign to Users <span className="text-red-500">*</span>
              </label>

              <div className="mb-3">
                <label className="block text-xs font-medium mb-1" style={LABEL_STYLE}>
                  Default Usage Limit Per User
                </label>
                <input
                  type="number"
                  value={defaultUserLimit}
                  onChange={(e) => {
                    const limit = parseInt(e.target.value) || 1;
                    setDefaultUserLimit(limit);
                    const newLimits: Record<string, number> = {};
                    selectedUsers.forEach((user) => {
                      newLimits[user.value] = limit;
                    });
                    setUserUsageLimits(newLimits);
                  }}
                  min="1"
                  className="w-24 px-3 py-2 rounded-lg text-sm"
                  style={INPUT_STYLE}
                />
              </div>

              <AsyncSelect<SelectOption, true>
                instanceId="user-assign-select"
                cacheOptions
                defaultOptions
                loadOptions={loadOptions}
                value={selectedUsers}
                onChange={handleUsersChange}
                placeholder="Search users by name or email..."
                isMulti
                isSearchable
                isClearable
                styles={selectStyles}
                noOptionsMessage={({ inputValue }) =>
                  inputValue.length < 2
                    ? 'Type 2+ characters'
                    : 'No users found'
                }
                closeMenuOnSelect={false}
                hideSelectedOptions={false}
              />
              {errors.users && (
                <p className="text-xs mt-1" style={{ color: 'var(--color-danger)' }}>
                  {errors.users}
                </p>
              )}

              {selectedUsers.length > 0 && (
                <div className="mt-3 space-y-2">
                  <label className="block text-xs font-medium" style={LABEL_STYLE}>
                    Individual Usage Limits
                  </label>
                  <div className="space-y-2 max-h-48 overflow-y-auto">
                    {selectedUsers.map((user, index) => (
                      <div
                        key={`user-assign-${user.value}-${index}`}
                        className="flex items-center justify-between gap-3 px-3 py-2 rounded-lg"
                        style={{
                          background: 'var(--color-surface-alt)',
                          border: '1px solid var(--color-border)',
                        }}
                      >
                        <p className="text-sm truncate flex-1">{user.label}</p>
                        <div className="flex items-center gap-2">
                          <label className="text-xs">Uses:</label>
                          <input
                            type="number"
                            value={userUsageLimits[user.value] || 1}
                            onChange={(e) =>
                              handleUserLimitChange(
                                user.value,
                                parseInt(e.target.value) || 1,
                              )
                            }
                            min="1"
                            max="999"
                            className="w-16 px-2 py-1 rounded text-sm text-center"
                            style={INPUT_STYLE}
                          />
                          <button
                            type="button"
                            onClick={() => {
                              setSelectedUsers((prev) =>
                                prev.filter((u) => u.value !== user.value),
                              );
                              setUserUsageLimits((prev) => {
                                const next = { ...prev };
                                delete next[user.value];
                                return next;
                              });
                            }}
                            className="p-1 rounded hover:bg-red-50"
                            style={{ color: 'var(--color-danger)' }}
                          >
                            <svg
                              width="14"
                              height="14"
                              viewBox="0 0 24 24"
                              fill="none"
                              stroke="currentColor"
                              strokeWidth="2"
                            >
                              <path d="M18 6L6 18M6 6l12 12" />
                            </svg>
                          </button>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              )}
            </div>
          )}

          {/* ── Applicable Items ─────────────────────────────────────── */}
          <div>
            <label className="block text-sm font-medium mb-2" style={LABEL_STYLE}>
              Applicable To <span className="text-red-500">*</span>
            </label>

            <div className="flex flex-wrap gap-2 mb-3">
              {(['all', 'category', 'product'] as const).map((type) => (
                <button
                  key={`applicable-${type}`}
                  type="button"
                  onClick={() => handleApplicableTypeChange(type)}
                  className="px-4 py-2 rounded-lg text-sm font-medium transition-all capitalize"
                  style={{
                    background:
                      applicableType === type
                        ? 'var(--color-cta)'
                        : 'var(--color-surface-alt)',
                    color:
                      applicableType === type
                        ? 'white'
                        : 'var(--color-text-secondary)',
                    border:
                      applicableType === type
                        ? 'none'
                        : '1px solid var(--color-border)',
                  }}
                >
                  {type === 'all'
                    ? 'All Products'
                    : type === 'category'
                      ? 'Categories'
                      : 'Products'}
                </button>
              ))}
            </div>

            {applicableType === 'category' && (
              <div>
                <Select<SelectOption, true>
                  instanceId="category-select"
                  options={categoryOptions}
                  value={selectedCategories}
                  onChange={(newValue) => setSelectedCategories(newValue)}
                  placeholder="Search categories..."
                  isMulti
                  isSearchable
                  isClearable
                  styles={selectStyles}
                  noOptionsMessage={() => 'No categories found'}
                  closeMenuOnSelect={false}
                  hideSelectedOptions={false}
                />
                {errors.applicable && (
                  <p className="text-xs mt-1" style={{ color: 'var(--color-danger)' }}>
                    {errors.applicable}
                  </p>
                )}
                <p
                  className="text-xs mt-1"
                  style={{ color: 'var(--color-text-tertiary)' }}
                >
                  {selectedCategories.length} selected
                </p>
              </div>
            )}

            {applicableType === 'product' && (
              <div>
                <Select<SelectOption, true>
                  instanceId="product-select"
                  options={productOptions}
                  value={selectedProducts}
                  onChange={(newValue) => setSelectedProducts(newValue)}
                  placeholder="Search products..."
                  isMulti
                  isSearchable
                  isClearable
                  styles={selectStyles}
                  noOptionsMessage={() => 'No products found'}
                  closeMenuOnSelect={false}
                  hideSelectedOptions={false}
                />
                {errors.applicable && (
                  <p className="text-xs mt-1" style={{ color: 'var(--color-danger)' }}>
                    {errors.applicable}
                  </p>
                )}
                <p
                  className="text-xs mt-1"
                  style={{ color: 'var(--color-text-tertiary)' }}
                >
                  {selectedProducts.length} selected
                </p>
              </div>
            )}

            {applicableType === 'all' && (
              <div
                className="px-4 py-3 rounded-lg text-sm"
                style={{
                  background: 'var(--color-surface-alt)',
                  border: '1px solid var(--color-border)',
                }}
              >
                <span style={{ color: 'var(--color-text-secondary)' }}>
                  This coupon will apply to <strong>all products</strong>.
                </span>
              </div>
            )}
          </div>

          {/* ── Offer & Featured Toggles ─────────────────────────────── */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium mb-1.5" style={LABEL_STYLE}>
                Show as Offer
              </label>
              <button
                type="button"
                onClick={() => handleToggle('is_offer')}
                className="px-4 py-2 rounded-lg text-sm font-medium transition-all"
                style={{
                  background: formData.is_offer
                    ? 'var(--color-cta)'
                    : 'var(--color-surface-alt)',
                  border: formData.is_offer ? 'none' : '1px solid var(--color-border)',
                  color: formData.is_offer ? 'white' : 'var(--color-text-secondary)',
                }}
              >
                {formData.is_offer ? '🏷️ Offer Enabled' : 'Regular Coupon'}
              </button>
            </div>
            <div>
              <label className="block text-sm font-medium mb-1.5" style={LABEL_STYLE}>
                Featured on Homepage
              </label>
              <button
                type="button"
                onClick={() => handleToggle('is_featured')}
                className="px-4 py-2 rounded-lg text-sm font-medium transition-all"
                style={{
                  background: formData.is_featured
                    ? 'var(--color-success)'
                    : 'var(--color-surface-alt)',
                  border: formData.is_featured
                    ? 'none'
                    : '1px solid var(--color-border)',
                  color: formData.is_featured ? 'white' : 'var(--color-text-secondary)',
                }}
              >
                {formData.is_featured ? '⭐ Featured' : 'Not Featured'}
              </button>
            </div>
          </div>

          {/* ── Multi-language Translations ──────────────────────────── */}
          {isMultiLang && formData.is_offer && (
            <div>
              <label className="block text-sm font-medium mb-3" style={LABEL_STYLE}>
                Offer Translations (Multi-language)
              </label>

              {/* Language Tabs */}
              <div
                className="flex flex-wrap gap-1 border-b mb-3"
                style={{ borderColor: 'var(--color-border)' }}
              >
                {activeLanguages.map((lang) => (
                  <button
                    key={`lang-tab-${lang.code}`}
                    type="button"
                    onClick={() => setActiveLangTab(lang.code)}
                    className={`px-3 py-2 text-sm font-medium transition-all border-b-2 whitespace-nowrap ${
                      activeLangTab === lang.code
                        ? 'border-cta text-cta'
                        : 'border-transparent text-text-secondary hover:text-text'
                    }`}
                    style={{
                      color:
                        activeLangTab === lang.code ? 'var(--color-cta)' : undefined,
                      borderColor:
                        activeLangTab === lang.code
                          ? 'var(--color-cta)'
                          : undefined,
                    }}
                  >
                    {lang.name_native || lang.name} {lang.is_default ? '⭐' : ''}
                  </button>
                ))}
              </div>

              {/* Translation Panels */}
              {activeLanguages.map((lang, index) => {
                const trans = getTranslation(lang.code);
                return (
                  <div
                    key={`trans-panel-${lang.code}-${index}`}
                    className={activeLangTab === lang.code ? 'block' : 'hidden'}
                  >
                    <div className="space-y-3">
                      <div>
                        <label
                          className="block text-xs font-medium mb-1"
                          style={LABEL_STYLE}
                        >
                          Offer Title ({lang.name})
                        </label>
                        <input
                          type="text"
                          value={trans.offer_title || ''}
                          onChange={(e) =>
                            handleTranslationChange(
                              lang.code,
                              'offer_title',
                              e.target.value,
                            )
                          }
                          placeholder={`e.g., Eid Special Sale`}
                          maxLength={200}
                          className="w-full px-4 py-2.5 rounded-lg text-sm outline-none"
                          style={INPUT_STYLE}
                        />
                      </div>
                      <div>
                        <label
                          className="block text-xs font-medium mb-1"
                          style={LABEL_STYLE}
                        >
                          Badge Text ({lang.name})
                        </label>
                        <input
                          type="text"
                          value={trans.offer_badge || ''}
                          onChange={(e) =>
                            handleTranslationChange(
                              lang.code,
                              'offer_badge',
                              e.target.value,
                            )
                          }
                          placeholder={`e.g., 🔥 Hot Deal`}
                          maxLength={50}
                          className="w-full px-4 py-2.5 rounded-lg text-sm outline-none"
                          style={INPUT_STYLE}
                        />
                      </div>
                      <div>
                        <label
                          className="block text-xs font-medium mb-1"
                          style={LABEL_STYLE}
                        >
                          Description ({lang.name})
                        </label>
                        <textarea
                          rows={2}
                          value={trans.offer_description || ''}
                          onChange={(e) =>
                            handleTranslationChange(
                              lang.code,
                              'offer_description',
                              e.target.value,
                            )
                          }
                          placeholder={`Describe the offer...`}
                          className="w-full px-4 py-2.5 rounded-lg text-sm outline-none resize-none"
                          style={INPUT_STYLE}
                        />
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>
          )}

          {/* ── Status Toggle ────────────────────────────────────────── */}
          <div>
            <label className="block text-sm font-medium mb-1.5" style={LABEL_STYLE}>
              Active Status
            </label>
            <button
              type="button"
              onClick={() => handleToggle('is_active')}
              className="px-4 py-2 rounded-lg text-sm font-medium transition-all"
              style={{
                background: formData.is_active
                  ? 'var(--color-success)'
                  : 'var(--color-surface-alt)',
                border: formData.is_active ? 'none' : '1px solid var(--color-border)',
                color: formData.is_active ? 'white' : 'var(--color-text-secondary)',
              }}
            >
              {formData.is_active ? '✅ Active' : '❌ Inactive'}
            </button>
          </div>

          {/* ── Form Actions ──────────────────────────────────────────── */}
          <div
            className="flex gap-3 pt-4 border-t"
            style={{ borderColor: 'var(--color-border)' }}
          >
            <button
              type="submit"
              disabled={loading}
              className="px-6 py-2.5 rounded-lg text-sm font-medium transition-all disabled:opacity-50 hover:opacity-90"
              style={{ background: 'var(--color-cta)', color: 'white' }}
            >
              {loading
                ? 'Saving...'
                : isEditing
                  ? 'Update Coupon'
                  : 'Create Coupon'}
            </button>
            <button
              type="button"
              onClick={() => router.back()}
              className="px-6 py-2.5 rounded-lg text-sm font-medium transition-all hover:opacity-80"
              style={{
                background: 'var(--color-surface-alt)',
                color: 'var(--color-text)',
                border: '1px solid var(--color-border)',
              }}
            >
              Cancel
            </button>
          </div>
        </div>
      </form>
    </div>
  );
}