'use client';

import { useMemo, useRef, useState, useTransition } from 'react';
import { useRouter } from 'next/navigation';
import { Check, ChevronsUpDown, PlusCircle, Trash2 } from 'lucide-react';
import { cn } from '@/lib/utils';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Textarea } from '@/components/ui/textarea';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { Checkbox } from '@/components/ui/checkbox';
import { useToast } from '@/hooks/use-toast';
import { handleCreateCampaign, handleUpdateCampaign } from '@/lib/actions';
import type { Campaign, ChartOfAccount, ProductionItem } from '@/lib/types';

type CampaignItemDraft = {
  id: string;
  productId: string;
  minQty: string;
  bundlePrice: string;
  regularUnitPrice: string;
  maxApplications: string;
};

type CampaignEditorPageProps = {
  mode: 'create' | 'edit' | 'duplicate';
  campaign?: Campaign | null;
  materials: ProductionItem[];
  accounts: ChartOfAccount[];
  customerCategoryOptions?: Array<{ id: string; name: string }>;
  t: any;
  tGlobal: any;
};

export default function CampaignEditorPage({
  mode,
  campaign,
  materials,
  accounts,
  customerCategoryOptions = [],
  t,
  tGlobal,
}: CampaignEditorPageProps) {
  const router = useRouter();
  const { toast } = useToast();
  const [isPending, startTransition] = useTransition();

  const customerScopeOptions = useMemo(() => {
    const normalized = Array.from(
      new Map(
        (customerCategoryOptions || [])
          .map((option) => ({
            id: String(option?.id || '').trim(),
            name: String(option?.name || option?.id || '').trim(),
          }))
          .filter((option) => option.id.length > 0)
          .map((option) => [option.id, option]),
      ).values(),
    );
    const fallback = [
      { id: 'general', name: 'general' },
      { id: 'wholesale', name: 'wholesale' },
      { id: 'vip', name: 'vip' },
    ];
    const base = normalized.length > 0 ? normalized : fallback;
    return [{ id: 'all', name: t?.allCustomers ?? 'الكل' }, ...base.filter((option) => option.id !== 'all')];
  }, [customerCategoryOptions, t?.allCustomers]);

  const [activeTab, setActiveTab] = useState<'info' | 'items' | 'scope' | 'accounting'>('info');
  const [productPickerOpenId, setProductPickerOpenId] = useState('');
  const [productSearch, setProductSearch] = useState('');
  const productSearchInputRef = useRef<HTMLInputElement | null>(null);
  const [previewQuantity, setPreviewQuantity] = useState('7');

  const [name, setName] = useState(
    mode === 'duplicate'
      ? `${String(campaign?.name || '').trim()} ${t?.copySuffix ?? '(نسخة)'}`.trim()
      : String(campaign?.name || ''),
  );
  const [startDate, setStartDate] = useState(String(campaign?.startDate || '').slice(0, 10));
  const [endDate, setEndDate] = useState(String(campaign?.endDate || '').slice(0, 10));
  const [status, setStatus] = useState<'active' | 'scheduled' | 'expired' | 'inactive'>((campaign?.status || 'active') as 'active' | 'scheduled' | 'expired' | 'inactive');
  const [description, setDescription] = useState(String(campaign?.description || ''));
  const loadedBranchIds = Array.isArray(campaign?.branchIds) ? campaign?.branchIds.filter(Boolean) : [];
  const loadedCustomerTags = Array.isArray(campaign?.customerTags) && campaign?.customerTags.length > 0
    ? campaign.customerTags.filter(Boolean)
    : ['all'];
  const [branchScopeMode, setBranchScopeMode] = useState<'all' | 'selected'>(loadedBranchIds.length > 0 ? 'selected' : 'all');
  const [branchIdsText, setBranchIdsText] = useState(loadedBranchIds.join(', '));
  const [customerTags, setCustomerTags] = useState<string[]>(loadedCustomerTags);
  const [autoApplyInPos, setAutoApplyInPos] = useState(campaign?.autoApplyInPos !== false);
  const [allowRepeats, setAllowRepeats] = useState(campaign?.allowRepeats !== false);
  const [allowStacking, setAllowStacking] = useState(campaign?.allowStacking === true);
  const [priority, setPriority] = useState(String(Number(campaign?.priority || 0)));
  const [maxApplicationsPerInvoice, setMaxApplicationsPerInvoice] = useState(String(Number(campaign?.maxApplicationsPerInvoice || 0)));
  const [bundlePriceBlurredIds, setBundlePriceBlurredIds] = useState<string[]>([]);
  const [items, setItems] = useState<CampaignItemDraft[]>(
    (campaign?.items || []).length > 0
      ? (campaign?.items || []).map((item) => ({
          id: String(item.id || `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`),
          productId: String(item.productId || ''),
          minQty: String(item.minQty || ''),
          bundlePrice: String(item.bundlePrice || ''),
          regularUnitPrice: String(item.regularUnitPrice || ''),
          maxApplications: String(item.maxApplications || ''),
        }))
      : [{ id: `${Date.now()}-0`, productId: '', minQty: '3', bundlePrice: '', regularUnitPrice: '', maxApplications: '' }],
  );

  const materialsById = useMemo(
    () => new Map((materials || []).map((material) => [String(material.id || '').trim(), material])),
    [materials],
  );

  const accountByCode = useMemo(() => {
    return new Map(
      (accounts || [])
        .filter((entry) => String(entry.type || '') === 'account')
        .map((entry) => [String(entry.code || '').trim(), entry]),
    );
  }, [accounts]);

  const accountingRows = useMemo(() => {
    const resolve = (code: string, fallback: string) => {
      const account = accountByCode.get(code);
      return {
        code,
        name: String(account?.nameAr || account?.nameEn || fallback),
      };
    };

    return [
      resolve('4110', 'إيرادات المبيعات'),
      resolve('4120', 'خصم مسموح به'),
      resolve('4121', 'خصم حملات تسويقية'),
      resolve('4122', 'خصم بونص ترويجي'),
      resolve('4130', 'مردودات مبيعات'),
    ];
  }, [accountByCode]);

  const formatPrice = (value?: number) => {
    if (!Number.isFinite(Number(value))) return '';
    return Number(value).toFixed(2);
  };

  const normalizeSearchText = (input: string) => {
    return String(input || '')
      .toLowerCase()
      .replace(/[\u064B-\u065F\u0670]/g, '')
      .replace(/[إأآٱ]/g, 'ا')
      .replace(/ى/g, 'ي')
      .replace(/ؤ/g, 'و')
      .replace(/ئ/g, 'ي')
      .replace(/ة/g, 'ه')
      .replace(/[^\p{L}\p{N}]+/gu, '');
  };

  const matchesMaterialSearch = (material: ProductionItem, query: string) => {
    const trimmed = String(query || '').trim();
    if (!trimmed) return true;

    const tokens = trimmed
      .split(/\s+/)
      .map((part) => normalizeSearchText(part))
      .filter(Boolean);

    if (tokens.length === 0) return true;

    const normalizedName = normalizeSearchText(material.name || '');
    const normalizedNumber = normalizeSearchText(String(material.itemNumber || material.id || ''));
    const normalizedBarcode = normalizeSearchText(material.barcode || '');
    const normalizedSecondaryBarcode = normalizeSearchText(material.secondaryBarcode || '');
    const normalizedExtra = (material.additionalBarcodes || [])
      .map((code) => normalizeSearchText(code || ''))
      .join(' ');
    const normalizedAdditionalDetails = normalizeSearchText(material.additionalDetails || '');

    return tokens.every((token) =>
      normalizedName.includes(token)
      || normalizedNumber.includes(token)
      || normalizedBarcode.includes(token)
      || normalizedSecondaryBarcode.includes(token)
      || normalizedExtra.includes(token)
      || normalizedAdditionalDetails.includes(token),
    );
  };

  const filteredMaterials = useMemo(() => {
    const query = String(productSearch || '').trim();
    if (!query) return materials || [];
    return (materials || []).filter((material) => matchesMaterialSearch(material, query));
  }, [materials, productSearch]);

  const hasInvalidBundlePricing = (entry: CampaignItemDraft) => {
    const material = materialsById.get(entry.productId);
    const salePrice = Number(material?.salePrice || 0);
    const minQty = Number(entry.minQty || 0);
    const bundlePrice = Number(entry.bundlePrice || 0);

    if (!entry.productId || salePrice <= 0 || minQty <= 0 || bundlePrice <= 0) return false;
    return bundlePrice > salePrice * minQty;
  };

  const getOfferUnitPrice = (entry: CampaignItemDraft) => {
    const minQty = Number(entry.minQty || 0);
    const bundlePrice = Number(entry.bundlePrice || 0);
    if (minQty <= 0 || bundlePrice <= 0) return null;
    return bundlePrice / minQty;
  };

  const getOfferDiscountPct = (entry: CampaignItemDraft) => {
    const material = materialsById.get(entry.productId);
    const salePrice = Number(material?.salePrice || 0);
    const minQty = Number(entry.minQty || 0);
    const bundlePrice = Number(entry.bundlePrice || 0);
    if (salePrice <= 0 || minQty <= 0 || bundlePrice <= 0) return null;
    const normalTotal = salePrice * minQty;
    if (normalTotal <= 0) return null;
    const pct = ((normalTotal - bundlePrice) / normalTotal) * 100;
    return Number(pct.toFixed(2));
  };

  const getBundleProfitLoss = (entry: CampaignItemDraft) => {
    const material = materialsById.get(entry.productId);
    const purchasePrice = Number(material?.purchasePrice || 0);
    const minQty = Number(entry.minQty || 0);
    const bundlePrice = Number(entry.bundlePrice || 0);
    if (purchasePrice <= 0 || minQty <= 0 || bundlePrice <= 0) return null;

    const totalCost = purchasePrice * minQty;
    const diff = bundlePrice - totalCost;
    const pct = totalCost > 0 ? (diff / totalCost) * 100 : 0;
    return {
      amount: Number(diff.toFixed(2)),
      percent: Number(pct.toFixed(2)),
      totalCost: Number(totalCost.toFixed(2)),
    };
  };

  const hasBlockingRowErrors = useMemo(() => items.some((entry) => hasInvalidBundlePricing(entry)), [items]);

  const addItemRow = () => {
    setItems((current) => [
      ...current,
      { id: `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`, productId: '', minQty: '3', bundlePrice: '', regularUnitPrice: '', maxApplications: '' },
    ]);
  };

  const removeItemRow = (id: string) => {
    setItems((current) => current.length <= 1 ? current : current.filter((entry) => entry.id !== id));
  };

  const updateItemRow = (id: string, field: keyof CampaignItemDraft, value: string) => {
    setItems((current) => current.map((entry) => (entry.id === id ? { ...entry, [field]: value } : entry)));
  };

  const onCreateOrUpdate = () => {
    if (!name.trim()) {
      toast({ title: tGlobal?.error ?? 'خطأ', description: t?.campaignNameRequired ?? 'اسم الحملة مطلوب.', variant: 'destructive' });
      return;
    }
    if (!startDate || !endDate) {
      toast({ title: tGlobal?.error ?? 'خطأ', description: t?.campaignDatesRequired ?? 'تاريخ البداية والنهاية مطلوبان.', variant: 'destructive' });
      return;
    }

    const normalizedItems = items
      .map((entry) => ({
        productId: String(entry.productId || '').trim(),
        minQty: Number(entry.minQty || 0),
        bundlePrice: Number(entry.bundlePrice || 0),
        regularUnitPrice: Number(entry.regularUnitPrice || 0),
        maxApplications: Number(entry.maxApplications || 0),
      }))
      .filter((entry) => entry.productId && entry.minQty > 0 && entry.bundlePrice > 0);

    if (normalizedItems.length === 0) {
      toast({ title: tGlobal?.error ?? 'خطأ', description: t?.campaignItemsRequired ?? 'أضف صنفًا واحدًا على الأقل مع الكمية والسعر.', variant: 'destructive' });
      return;
    }

    if (hasBlockingRowErrors) {
      toast({ title: tGlobal?.error ?? 'خطأ', description: t?.fixPricingWarnings ?? 'يوجد تسعير غير منطقي في بعض الصفوف.', variant: 'destructive' });
      setActiveTab('items');
      return;
    }

    const parsedBranchIds = branchScopeMode === 'all'
      ? []
      : String(branchIdsText || '')
          .split(',')
          .map((value) => value.trim())
          .filter(Boolean);

    startTransition(async () => {
      const payload = {
        name: name.trim(),
        type: 'multi_buy' as const,
        startDate,
        endDate,
        status,
        description: description.trim(),
        branchIds: parsedBranchIds,
        customerTags,
        autoApplyInPos,
        allowRepeats,
        allowStacking,
        priority: Number(priority || 0),
        maxApplicationsPerInvoice: Number(maxApplicationsPerInvoice || 0),
        items: normalizedItems.map((entry) => ({
          productId: entry.productId,
          minQty: entry.minQty,
          bundlePrice: entry.bundlePrice,
          regularUnitPrice: entry.regularUnitPrice > 0 ? entry.regularUnitPrice : undefined,
          maxApplications: entry.maxApplications > 0 ? entry.maxApplications : undefined,
        })),
      };

      const result = mode === 'edit' && campaign?.id
        ? await handleUpdateCampaign({ campaignId: campaign.id, ...payload })
        : await handleCreateCampaign(payload);

      if ((result as any)?.success) {
        toast({ title: mode === 'edit' ? t?.campaignUpdated ?? 'تم تحديث الحملة بنجاح' : t?.campaignCreated ?? 'تم إنشاء الحملة بنجاح' });
        router.push('/admin/data/campaigns');
        router.refresh();
      } else {
        toast({
          title: tGlobal?.error ?? 'خطأ',
          description: String((result as any)?.error || (mode === 'edit' ? t?.campaignUpdateFailed ?? 'تعذر تحديث الحملة.' : t?.campaignCreateFailed || 'تعذر إنشاء الحملة.')),
          variant: 'destructive',
        });
      }
    });
  };

  const pageTitle = mode === 'edit'
    ? (t?.editTitle ?? 'تعديل الحملة')
    : (t?.createTitle ?? 'إنشاء حملة جديدة');

  const pageDescription = mode === 'edit'
    ? (t?.editDescription ?? 'حدّث بيانات الحملة ثم احفظ التعديلات.')
    : (t?.createDescription ?? 'أدخل بيانات الحملة، ثم أضف الأصناف وآلية Multi-Buy.');

  return (
    <Card>
      <CardHeader>
        <CardTitle>{pageTitle}</CardTitle>
        <CardDescription>{pageDescription}</CardDescription>
      </CardHeader>
      <CardContent className="space-y-4">
        <Tabs value={activeTab} onValueChange={(value) => setActiveTab(value as 'info' | 'items' | 'scope' | 'accounting')} className="w-full">
          <TabsList className="w-full flex-wrap h-auto justify-start">
            <TabsTrigger value="info">{t?.tabInfo ?? 'المعلومات'}</TabsTrigger>
            <TabsTrigger value="items">{t?.tabItems ?? 'الأصناف والعرض'}</TabsTrigger>
            <TabsTrigger value="scope">{t?.tabScope ?? 'القيود والإعدادات'}</TabsTrigger>
            <TabsTrigger value="accounting">{t?.tabAccounting ?? 'المحاسبة'}</TabsTrigger>
          </TabsList>

          <TabsContent value="info" className="space-y-3">
            <div className="grid gap-3 md:grid-cols-2">
              <div className="space-y-1 rounded-md border bg-muted/20 p-3">
                <Label>{t?.nameLabel ?? 'اسم الحملة'}</Label>
                <Input value={name} onChange={(event) => setName(event.target.value)} />
              </div>
              <div className="space-y-1 rounded-md border bg-muted/20 p-3">
                <Label>{t?.statusLabel ?? 'الحالة'}</Label>
                <Select value={status} onValueChange={(value) => setStatus(value as 'active' | 'scheduled' | 'expired' | 'inactive')}>
                  <SelectTrigger><SelectValue /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value="active">{t?.statusActive ?? 'نشطة'}</SelectItem>
                    <SelectItem value="scheduled">{t?.statusScheduled ?? 'مجدولة'}</SelectItem>
                    <SelectItem value="expired">{t?.statusExpired ?? 'منتهية'}</SelectItem>
                    <SelectItem value="inactive">{t?.statusInactive ?? 'متوقفة'}</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-1 rounded-md border bg-muted/20 p-3">
                <Label>{t?.startDateLabel ?? 'تاريخ البداية'}</Label>
                <Input type="date" value={startDate} onChange={(event) => setStartDate(event.target.value)} />
              </div>
              <div className="space-y-1 rounded-md border bg-muted/20 p-3">
                <Label>{t?.endDateLabel ?? 'تاريخ النهاية'}</Label>
                <Input type="date" value={endDate} onChange={(event) => setEndDate(event.target.value)} />
              </div>
              <div className="space-y-1 rounded-md border bg-muted/20 p-3 md:col-span-2">
                <Label>{t?.descriptionLabel ?? 'الوصف'}</Label>
                <Textarea value={description} onChange={(event) => setDescription(event.target.value)} rows={3} />
              </div>
            </div>
          </TabsContent>

          <TabsContent value="items" className="space-y-3">
            <div className="space-y-3 rounded-md border bg-muted/10 p-4">
              <div className="flex items-center justify-between">
                <p className="font-medium">{t?.campaignItemsTitle ?? 'تفاصيل الحملة (Multi-Buy)'}</p>
                <Button type="button" variant="outline" onClick={addItemRow}>
                  <PlusCircle className="me-2 h-4 w-4" />
                  {t?.addItemRow ?? 'إضافة صنف'}
                </Button>
              </div>
              <div className="rounded-md border bg-background overflow-x-auto">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>{t?.materialLabel ?? 'الصنف'}</TableHead>
                      <TableHead>{t?.minQtyLabel ?? 'الكمية المطلوبة'}</TableHead>
                      <TableHead>{t?.bundlePriceLabel ?? 'سعر الباقة'}</TableHead>
                      <TableHead>{t?.maxApplicationsLabel ?? 'حد التكرار'}</TableHead>
                      <TableHead>{t?.actionsLabel ?? 'إجراءات'}</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {items.map((entry) => {
                      const selectedMaterial = materialsById.get(entry.productId);
                      const pricingWarning = hasInvalidBundlePricing(entry);
                      const offerUnitPrice = getOfferUnitPrice(entry);
                      const offerDiscountPct = getOfferDiscountPct(entry);
                      const bundleProfitLoss = getBundleProfitLoss(entry);
                      const showProfitLossHint = bundlePriceBlurredIds.includes(entry.id) && bundleProfitLoss !== null;
                      return (
                        <TableRow key={entry.id}>
                          <TableCell className="min-w-[260px] align-top">
                            <Popover
                              open={productPickerOpenId === entry.id}
                              onOpenChange={(open) => {
                                setProductPickerOpenId(open ? entry.id : '');
                                if (open) {
                                  setProductSearch('');
                                  setTimeout(() => {
                                    productSearchInputRef.current?.focus();
                                    productSearchInputRef.current?.select();
                                  }, 0);
                                }
                              }}
                            >
                              <PopoverTrigger asChild>
                                <Button type="button" variant="outline" role="combobox" className={cn('w-full justify-between', !entry.productId && 'text-muted-foreground')}>
                                  <span className="truncate text-start">{selectedMaterial?.name || (t?.selectMaterial ?? 'اختر الصنف')}</span>
                                  <ChevronsUpDown className="ms-2 h-4 w-4 shrink-0 opacity-50" />
                                </Button>
                              </PopoverTrigger>
                              <PopoverContent disablePortal className="w-[--radix-popover-trigger-width] p-0" align="start">
                                <div className="border-b p-2">
                                  <Input
                                    ref={productSearchInputRef}
                                    value={productSearch}
                                    onChange={(event) => setProductSearch(event.target.value)}
                                    placeholder={t?.searchMaterial ?? 'ابحث عن الصنف...'}
                                  />
                                </div>
                                <div className="max-h-60 overflow-y-auto">
                                  {filteredMaterials.length > 0 ? filteredMaterials.map((material) => (
                                    <button
                                      key={material.id}
                                      type="button"
                                      onClick={() => {
                                        updateItemRow(entry.id, 'productId', material.id);
                                        setProductPickerOpenId('');
                                        setProductSearch('');
                                      }}
                                      className={cn('flex w-full items-start gap-2 px-3 py-2 text-start text-sm hover:bg-accent', material.id === entry.productId && 'bg-accent')}
                                    >
                                      <Check className={cn('h-4 w-4', material.id === entry.productId ? 'opacity-100' : 'opacity-0')} />
                                      <div className="min-w-0 flex-1">
                                        <p className="truncate">{material.name}</p>
                                        <p className="truncate text-[11px] text-muted-foreground">{[material.itemNumber || material.id, material.barcode || material.secondaryBarcode].filter(Boolean).join(' • ') || '-'}</p>
                                      </div>
                                      <span className="mt-0.5 text-xs text-muted-foreground">{formatPrice(material.salePrice)}</span>
                                    </button>
                                  )) : <div className="px-3 py-4 text-center text-sm text-muted-foreground">{t?.noResults ?? 'لا توجد نتائج'}</div>}
                                </div>
                              </PopoverContent>
                            </Popover>
                            {(offerUnitPrice || offerDiscountPct !== null || showProfitLossHint) && (
                              <p className="mt-2 flex min-w-0 flex-wrap items-center gap-1 text-xs sm:whitespace-nowrap">
                                {offerUnitPrice && (
                                  <span className="text-muted-foreground">
                                    {t?.offerUnitPriceHint ?? 'سعر القطعة بعد العرض'}: {formatPrice(offerUnitPrice)}
                                  </span>
                                )}

                                {offerUnitPrice && (offerDiscountPct !== null || showProfitLossHint) && (
                                  <span className="text-muted-foreground">•</span>
                                )}

                                {offerDiscountPct !== null && (
                                  <span className={cn(offerDiscountPct > 0 ? 'text-emerald-700' : 'text-amber-700')}>
                                    {t?.smartHelperHint ?? 'اقتراح ذكي'}: {t?.discountText ?? 'خصم'} {Math.max(0, offerDiscountPct)}%
                                  </span>
                                )}

                                {offerDiscountPct !== null && showProfitLossHint && (
                                  <span className="text-muted-foreground">•</span>
                                )}

                                {showProfitLossHint && bundleProfitLoss && (
                                  <span className={cn('w-full sm:w-auto', bundleProfitLoss.amount > 0 ? 'text-emerald-700' : bundleProfitLoss.amount < 0 ? 'text-red-600' : 'text-amber-700')}>
                                    {bundleProfitLoss.amount > 0
                                      ? (t?.profitHint ?? 'ربح تقديري')
                                      : bundleProfitLoss.amount < 0
                                        ? (t?.lossHint ?? 'خسارة تقديرية')
                                        : (t?.breakEvenHint ?? 'نقطة تعادل')
                                    }
                                    : {formatPrice(Math.abs(bundleProfitLoss.amount))}
                                    {' • '}
                                    {t?.costLabel ?? 'التكلفة'}: {formatPrice(bundleProfitLoss.totalCost)}
                                    {' • '}
                                    {Math.abs(bundleProfitLoss.percent)}%
                                  </span>
                                )}
                              </p>
                            )}
                          </TableCell>
                          <TableCell className="min-w-[130px] align-top">
                            <Input type="number" min={1} value={entry.minQty} onChange={(event) => updateItemRow(entry.id, 'minQty', event.target.value)} />
                          </TableCell>
                          <TableCell className="min-w-[220px] align-top">
                            <Input
                              type="number"
                              min={0.01}
                              step="0.01"
                              value={entry.bundlePrice}
                              onChange={(event) => updateItemRow(entry.id, 'bundlePrice', event.target.value)}
                              onBlur={() => setBundlePriceBlurredIds((current) => current.includes(entry.id) ? current : [...current, entry.id])}
                              className={pricingWarning ? 'border-red-500 focus-visible:ring-red-500' : ''}
                            />
                            {pricingWarning && <p className="mt-1 text-xs text-red-600">{t?.bundlePriceWarning ?? 'سعر الباقة أعلى من السعر العادي لهذه الكمية.'}</p>}
                          </TableCell>
                          <TableCell className="min-w-[140px] align-top">
                            <Input type="number" min={0} step={1} value={entry.maxApplications} onChange={(event) => updateItemRow(entry.id, 'maxApplications', event.target.value)} />
                          </TableCell>
                          <TableCell className="align-top">
                            <Button type="button" variant="ghost" size="icon" onClick={() => removeItemRow(entry.id)}>
                              <Trash2 className="h-4 w-4" />
                            </Button>
                          </TableCell>
                        </TableRow>
                      );
                    })}
                  </TableBody>
                </Table>
              </div>
              <div className="rounded-md border bg-background p-3 space-y-2">
                <div className="flex items-center gap-2">
                  <Label className="text-sm">{t?.previewQtyLabel ?? 'كمية مثال للمعاينة'}</Label>
                  <Input className="h-8 w-28" type="number" min={1} value={previewQuantity} onChange={(event) => setPreviewQuantity(event.target.value)} />
                </div>
                <p className="text-sm text-muted-foreground">{t?.previewNote ?? 'تُستخدم هذه المعاينة لتصور تأثير العرض فقط.'}</p>
              </div>
            </div>
          </TabsContent>

          <TabsContent value="scope" className="space-y-3">
            <div className="rounded-md border p-3 space-y-3">
              <div className="space-y-2">
                <Label>{t?.branchScopeLabel ?? 'ينطبق على الفروع'}</Label>
                <Select value={branchScopeMode} onValueChange={(value) => setBranchScopeMode(value as 'all' | 'selected')}>
                  <SelectTrigger><SelectValue /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">{t?.allBranches ?? 'جميع الفروع'}</SelectItem>
                    <SelectItem value="selected">{t?.selectedBranches ?? 'فروع محددة'}</SelectItem>
                  </SelectContent>
                </Select>
                {branchScopeMode === 'selected' && (
                  <Input value={branchIdsText} onChange={(event) => setBranchIdsText(event.target.value)} placeholder={t?.branchIdsPlaceholder ?? 'اكتب معرفات الفروع مفصولة بفاصلة'} />
                )}
              </div>

              <div className="space-y-2">
                <Label>{t?.customerScopeLabel ?? 'عملاء الحملة'}</Label>
                <div className="grid grid-cols-2 sm:grid-cols-4 gap-2">
                  {customerScopeOptions.map((option) => (
                    <label key={option.id} className="flex items-center gap-2 rounded border p-2 text-sm">
                      <Checkbox
                        checked={customerTags.includes(option.id)}
                        onCheckedChange={(checked) => {
                          const enabled = checked === true;
                          setCustomerTags((current) => {
                            if (option.id === 'all') return enabled ? ['all'] : current.filter((value) => value !== 'all');
                            const withoutAll = current.filter((value) => value !== 'all');
                            if (enabled) return Array.from(new Set([...withoutAll, option.id]));
                            const next = withoutAll.filter((value) => value !== option.id);
                            return next.length === 0 ? ['all'] : next;
                          });
                        }}
                      />
                      <span>{option.id === 'all' || option.name.toLowerCase() === option.id.toLowerCase() ? option.name : `${option.name} - ${option.id}`}</span>
                    </label>
                  ))}
                </div>
              </div>
            </div>

            <div className="rounded-md border p-3 space-y-3">
              <p className="font-medium">{t?.advancedSettings ?? 'إعدادات متقدمة'}</p>
              <div className="grid gap-2">
                <label className="flex items-center gap-2 text-sm">
                  <Checkbox checked={autoApplyInPos} onCheckedChange={(checked) => setAutoApplyInPos(checked === true)} />
                  <span>{t?.autoApplyPos ?? 'تطبيق تلقائي في POS'}</span>
                </label>
                <label className="flex items-center gap-2 text-sm">
                  <Checkbox checked={allowRepeats} onCheckedChange={(checked) => setAllowRepeats(checked === true)} />
                  <span>{t?.allowRepeats ?? 'السماح بالتكرار'}</span>
                </label>
                <label className="flex items-center gap-2 text-sm">
                  <Checkbox checked={allowStacking} onCheckedChange={(checked) => setAllowStacking(checked === true)} />
                  <span>{t?.allowStacking ?? 'السماح بدمج مع عروض أخرى'}</span>
                </label>
              </div>
              <div className="grid gap-3 md:grid-cols-2">
                <div className="space-y-1">
                  <Label>{t?.priorityLabel ?? 'الأولوية'}</Label>
                  <Input type="number" min={0} step={1} value={priority} onChange={(event) => setPriority(event.target.value)} />
                </div>
                <div className="space-y-1">
                  <Label>{t?.maxApplicationsPerInvoiceLabel ?? 'حد التكرار لكل فاتورة'}</Label>
                  <Input type="number" min={0} step={1} value={maxApplicationsPerInvoice} onChange={(event) => setMaxApplicationsPerInvoice(event.target.value)} />
                </div>
              </div>
            </div>
          </TabsContent>

          <TabsContent value="accounting" className="space-y-3">
            <div className="rounded-md border p-4 space-y-3">
              <p className="text-sm text-muted-foreground">
                {t?.accountingHint ?? 'هذا القسم يعرض الحسابات التي يستخدمها النظام تلقائيًا عند ترحيل خصومات الحملة.'}
              </p>
              <div className="rounded-md border overflow-x-auto">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>رمز الحساب</TableHead>
                      <TableHead>اسم الحساب</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {accountingRows.map((row) => (
                      <TableRow key={row.code}>
                        <TableCell className="font-mono">{row.code}</TableCell>
                        <TableCell>{row.name}</TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
              <div className="rounded-md bg-muted/40 p-3 text-sm">
                <p className="font-medium mb-1">مثال ترحيل صحيح لبيع مع خصم حملة:</p>
                <p className="font-mono">من ح/ الصندوق 1</p>
                <p className="font-mono">من ح/ خصم حملات تسويقية 29</p>
                <p className="font-mono">إلى ح/ المبيعات 30</p>
              </div>
            </div>
          </TabsContent>
        </Tabs>

        <div className="flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2 gap-2">
          <Button type="button" variant="outline" onClick={() => router.push('/admin/data/campaigns')}>
            {tGlobal?.cancel ?? 'إلغاء'}
          </Button>
          <Button type="button" onClick={onCreateOrUpdate} disabled={isPending || hasBlockingRowErrors}>
            {mode === 'edit' ? t?.saveChangesButton ?? 'حفظ التعديلات' : t?.createButton ?? 'إنشاء'}
          </Button>
        </div>
      </CardContent>
    </Card>
  );
}
