'use client';

import { useMemo, useRef, useState, useTransition } from 'react';
import { useRouter } from 'next/navigation';
import { Check, ChevronsUpDown, Copy, Pencil, PlusCircle, Power, Trash2, AlertCircle } from 'lucide-react';
import { useDocumentLock } from '@/hooks/use-document-lock';
import { cn } from '@/lib/utils';
import { formatDateStable } from '@/lib/formatters';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Badge } from '@/components/ui/badge';
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, handleDeleteCampaign, handleUpdateCampaign } from '@/lib/actions';
import type { Campaign, ProductionItem } from '@/lib/types';

type CampaignItemDraft = {
  id: string;
  productId: string;
  minQty: string;
  bundlePrice: string;
  regularUnitPrice: string;
  maxApplications: string;
};

type CampaignsManagerProps = {
  campaigns: Campaign[];
  materials: ProductionItem[];
  customerCategoryOptions?: Array<{ id: string; name: string }>;
  t: any;
  tGlobal: any;
};

export default function CampaignsManager({ campaigns, materials, customerCategoryOptions = [], t, tGlobal }: CampaignsManagerProps) {
  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 router = useRouter();
  const { toast } = useToast();
  const [isPending, startTransition] = useTransition();
  const [showCreateDialog, setShowCreateDialog] = useState(false);
  const [editingCampaignId, setEditingCampaignId] = useState('');
  const [dialogTab, setDialogTab] = useState<'info' | 'items' | 'scope'>('info');
  
  // Document locking for campaigns
  const { lockStatus } = useDocumentLock('campaign', editingCampaignId);
  const [productPickerOpenId, setProductPickerOpenId] = useState('');
  const [productSearch, setProductSearch] = useState('');
  const productSearchInputRef = useRef<HTMLInputElement | null>(null);
  const [previewQuantity, setPreviewQuantity] = useState('7');

  const [name, setName] = useState('');
  const [startDate, setStartDate] = useState('');
  const [endDate, setEndDate] = useState('');
  const [status, setStatus] = useState<'active' | 'scheduled' | 'expired' | 'inactive'>('active');
  const [description, setDescription] = useState('');
  const [branchScopeMode, setBranchScopeMode] = useState<'all' | 'selected'>('all');
  const [branchIdsText, setBranchIdsText] = useState('');
  const [customerTags, setCustomerTags] = useState<string[]>(['all']);
  const [autoApplyInPos, setAutoApplyInPos] = useState(true);
  const [allowRepeats, setAllowRepeats] = useState(true);
  const [allowStacking, setAllowStacking] = useState(false);
  const [priority, setPriority] = useState('0');
  const [maxApplicationsPerInvoice, setMaxApplicationsPerInvoice] = useState('0');
  const [bundlePriceBlurredIds, setBundlePriceBlurredIds] = useState<string[]>([]);
  const [items, setItems] = useState<CampaignItemDraft[]>([
    { 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 resetForm = () => {
    setEditingCampaignId('');
    setDialogTab('info');
    setProductPickerOpenId('');
    setProductSearch('');
    setPreviewQuantity('7');
    setName('');
    setStartDate('');
    setEndDate('');
    setStatus('active');
    setDescription('');
    setBranchScopeMode('all');
    setBranchIdsText('');
    setCustomerTags(['all']);
    setAutoApplyInPos(true);
    setAllowRepeats(true);
    setAllowStacking(false);
    setPriority('0');
    setMaxApplicationsPerInvoice('0');
    setBundlePriceBlurredIds([]);
    setItems([{ id: `${Date.now()}-0`, productId: '', minQty: '3', bundlePrice: '', regularUnitPrice: '', maxApplications: '' }]);
  };

  const openCreateDialog = () => {
    router.push('/admin/data/campaigns/new');
  };

  const openEditDialog = (campaign: Campaign) => {
    router.push(`/admin/data/campaigns/${campaign.id}`);
  };

  const openDuplicateDialog = (campaign: Campaign) => {
    router.push(`/admin/data/campaigns/new?duplicateId=${encodeURIComponent(String(campaign.id || ''))}`);
  };

  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 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(() => {
    return items.some((entry) => hasInvalidBundlePricing(entry));
  }, [items]);

  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' });
      setDialogTab('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 = editingCampaignId
        ? await handleUpdateCampaign({ campaignId: editingCampaignId, ...payload })
        : await handleCreateCampaign(payload);

      if ((result as any)?.success) {
        toast({ title: editingCampaignId ? t?.campaignUpdated ?? 'تم تحديث الحملة بنجاح' : t?.campaignCreated ?? 'تم إنشاء الحملة بنجاح' });
        setShowCreateDialog(false);
        resetForm();
        router.refresh();
      } else {
        toast({
          title: tGlobal?.error ?? 'خطأ',
          description: String((result as any)?.error || (editingCampaignId ? t?.campaignUpdateFailed ?? 'تعذر تحديث الحملة.' : t?.campaignCreateFailed || 'تعذر إنشاء الحملة.')),
          variant: 'destructive',
        });
      }
    });
  };

  const onDelete = (campaignId: string) => {
    startTransition(async () => {
      const result = await handleDeleteCampaign({ campaignId });
      if ((result as any)?.success) {
        toast({ title: t?.campaignDeleted ?? 'تم حذف الحملة' });
        router.refresh();
      } else {
        toast({
          title: tGlobal?.error ?? 'خطأ',
          description: String((result as any)?.error || t?.campaignDeleteFailed || 'تعذر حذف الحملة.'),
          variant: 'destructive',
        });
      }
    });
  };

  const onToggleStatus = (campaign: Campaign) => {
    const nextStatus: 'active' | 'inactive' = campaign.status === 'active' ? 'inactive' : 'active';

    startTransition(async () => {
      const result = await handleUpdateCampaign({
        campaignId: campaign.id,
        name: String(campaign.name || '').trim(),
        type: campaign.type || 'multi_buy',
        startDate: String(campaign.startDate || ''),
        endDate: String(campaign.endDate || ''),
        status: nextStatus,
        description: String(campaign.description || ''),
        branchIds: Array.isArray(campaign.branchIds) ? campaign.branchIds : [],
        customerTags: Array.isArray(campaign.customerTags) && campaign.customerTags.length > 0 ? campaign.customerTags : ['all'],
        autoApplyInPos: campaign.autoApplyInPos !== false,
        allowRepeats: campaign.allowRepeats !== false,
        allowStacking: campaign.allowStacking === true,
        priority: Number(campaign.priority || 0),
        maxApplicationsPerInvoice: Number(campaign.maxApplicationsPerInvoice || 0),
        items: (campaign.items || []).map((item) => ({
          id: String(item.id || ''),
          productId: String(item.productId || ''),
          categoryId: String(item.categoryId || ''),
          minQty: Number(item.minQty || 0),
          bundlePrice: Number(item.bundlePrice || 0),
          regularUnitPrice: item.regularUnitPrice,
          maxApplications: item.maxApplications,
        })),
      });

      if ((result as any)?.success) {
        toast({ title: nextStatus === 'active' ? t?.campaignActivated ?? 'تم تفعيل الحملة' : t?.campaignDeactivated ?? 'تم إيقاف الحملة' });
        router.refresh();
      } else {
        toast({
          title: tGlobal?.error ?? 'خطأ',
          description: String((result as any)?.error || t?.campaignUpdateFailed || 'تعذر تحديث الحملة.'),
          variant: 'destructive',
        });
      }
    });
  };

  const statusLabel = (value: string) => {
    if (value === 'active') return t?.statusActive ?? 'نشطة';
    if (value === 'scheduled') return t?.statusScheduled ?? 'مجدولة';
    if (value === 'expired') return t?.statusExpired ?? 'منتهية';
    return t?.statusInactive ?? 'متوقفة';
  };

  const statusVariant = (value: string) => {
    if (value === 'active') return 'default';
    if (value === 'scheduled') return 'secondary';
    if (value === 'expired') return 'outline';
    return 'destructive';
  };

  return (
    <Card>
      <CardHeader>
        <CardTitle>{t?.title ?? 'الحملات والعروض'}</CardTitle>
        <CardDescription>{t?.description ?? 'إدارة عروض Multi-Buy مثل: 3 مقابل 10 مع تطبيقها تلقائيًا في البيع.'}</CardDescription>
      </CardHeader>
      <CardContent className="space-y-4">
        <div className="flex flex-wrap gap-3">
          <Button size="sm" onClick={openCreateDialog}>
            <PlusCircle className="me-2 h-4 w-4" />
            {t?.createButton ?? 'إنشاء حملة'}
          </Button>
        </div>

        <div className="rounded-md border overflow-x-auto">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>{t?.nameLabel ?? 'اسم الحملة'}</TableHead>
                <TableHead>{t?.periodLabel ?? 'الفترة'}</TableHead>
                <TableHead>{t?.statusLabel ?? 'الحالة'}</TableHead>
                <TableHead>{t?.itemsCountLabel ?? 'عدد أصناف الحملة'}</TableHead>
                <TableHead>{t?.actionsLabel ?? 'إجراءات'}</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {(campaigns || []).length === 0 ? (
                <TableRow>
                  <TableCell colSpan={5} className="h-24 text-center text-muted-foreground">
                    {t?.noCampaigns ?? 'لا توجد حملات حتى الآن.'}
                  </TableCell>
                </TableRow>
              ) : (
                (campaigns || []).map((campaign) => (
                  <TableRow key={campaign.id}>
                    <TableCell>
                      <div className="space-y-1">
                        <div className="font-medium">{campaign.name}</div>
                        <div className="text-xs text-muted-foreground">{campaign.description || '-'}</div>
                      </div>
                    </TableCell>
                    <TableCell>
                      {formatDateStable(campaign.startDate)} - {formatDateStable(campaign.endDate)}
                    </TableCell>
                    <TableCell>
                      <Badge variant={statusVariant(campaign.status)}>{statusLabel(campaign.status)}</Badge>
                    </TableCell>
                    <TableCell>{Number(campaign.items?.length || 0)}</TableCell>
                    <TableCell>
                      <div className="flex gap-2">
                        <Button type="button" variant="ghost" size="sm" onClick={() => openDuplicateDialog(campaign)} disabled={isPending}>
                          <Copy className="me-2 h-4 w-4" />
                          {t?.copyButton ?? 'نسخ'}
                        </Button>
                        <Button type="button" variant="secondary" size="sm" onClick={() => onToggleStatus(campaign)} disabled={isPending}>
                          <Power className="me-2 h-4 w-4" />
                          {campaign.status === 'active' ? t?.deactivateButton ?? 'إيقاف' : t?.activateButton ?? 'تفعيل'}
                        </Button>
                        <Button type="button" variant="outline" size="sm" onClick={() => openEditDialog(campaign)} disabled={isPending}>
                          <Pencil className="me-2 h-4 w-4" />
                          {t?.editButton ?? 'تعديل'}
                        </Button>
                        <Button type="button" variant="destructive" size="sm" onClick={() => onDelete(campaign.id)} disabled={isPending}>
                          <Trash2 className="me-2 h-4 w-4" />
                          {tGlobal?.delete ?? 'حذف'}
                        </Button>
                      </div>
                    </TableCell>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>
        </div>
      </CardContent>

      <Dialog open={showCreateDialog} onOpenChange={(open) => { setShowCreateDialog(open); if (!open) resetForm(); }}>
        <DialogContent className="w-[calc(100vw-1rem)] max-w-5xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>{editingCampaignId ? t?.editTitle ?? 'تعديل الحملة' : t?.createTitle ?? 'إنشاء حملة جديدة'}</DialogTitle>
            <DialogDescription>{editingCampaignId ? t?.editDescription ?? 'حدّث بيانات الحملة ثم احفظ التعديلات.' : t?.createDescription ?? 'أدخل بيانات الحملة، ثم أضف الأصناف وآلية Multi-Buy.'}</DialogDescription>
          </DialogHeader>

          {editingCampaignId && lockStatus.lockError && (
            <div className="rounded-md border border-amber-200 bg-amber-50 p-4 flex gap-3">
              <AlertCircle className="h-5 w-5 text-amber-600 mt-0.5 flex-shrink-0" />
              <div>
                <p className="font-medium text-amber-900">{lockStatus.lockError}</p>
                {lockStatus.lockedBy && (
                  <p className="text-sm text-amber-700 mt-1">
                    يتم تعديل السند من خلال المستخدم: {lockStatus.lockedBy.userName} - 
                    ولن يستطيع أي مستخدم آخر التعديل عليه حتى الانتهاء من التعديل
                  </p>
                )}
              </div>
            </div>
          )}

          <Tabs value={dialogTab} onValueChange={(value) => setDialogTab(value as 'info' | 'items' | 'scope')} 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>
            </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">{statusLabel('active')}</SelectItem>
                      <SelectItem value="scheduled">{statusLabel('scheduled')}</SelectItem>
                      <SelectItem value="expired">{statusLabel('expired')}</SelectItem>
                      <SelectItem value="inactive">{statusLabel('inactive')}</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"
                                  onOpenAutoFocus={(event) => {
                                    event.preventDefault();
                                    setTimeout(() => {
                                      productSearchInputRef.current?.focus();
                                      productSearchInputRef.current?.select();
                                    }, 0);
                                  }}
                                >
                                  <div className="border-b p-2">
                                    <Input
                                      ref={productSearchInputRef}
                                      value={productSearch}
                                      onChange={(event) => setProductSearch(event.target.value)}
                                      placeholder={t?.searchMaterial ?? 'ابحث عن الصنف...'}
                                      onKeyDown={(event) => {
                                        event.stopPropagation();
                                      }}
                                    />
                                  </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 items-center gap-1 overflow-hidden whitespace-nowrap text-xs">
                                  {offerUnitPrice && (
                                    <span className="truncate text-muted-foreground">
                                      {t?.offerUnitPriceHint ?? 'سعر القطعة بعد العرض'}: {formatPrice(offerUnitPrice)}
                                    </span>
                                  )}

                                  {offerUnitPrice && (offerDiscountPct !== null || showProfitLossHint) && (
                                    <span className="text-muted-foreground">•</span>
                                  )}

                                  {offerDiscountPct !== null && (
                                    <span className={cn('truncate', 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 && (
                                    <span className={cn('truncate', 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>
                  <div className="space-y-2 text-sm">
                    {items
                      .map((entry) => {
                        const material = materialsById.get(entry.productId);
                        const minQty = Number(entry.minQty || 0);
                        const bundlePrice = Number(entry.bundlePrice || 0);
                        const maxApps = Number(entry.maxApplications || 0);
                        const salePrice = Number(material?.salePrice || 0);
                        const qty = Math.max(0, Number(previewQuantity || 0));
                        if (!material || minQty <= 0 || bundlePrice <= 0 || salePrice <= 0 || qty <= 0) return null;

                        let bundles = Math.floor(qty / minQty);
                        if (!allowRepeats) bundles = Math.min(1, bundles);
                        if (maxApps > 0) bundles = Math.min(bundles, maxApps);

                        const regularQty = qty - bundles * minQty;
                        const total = bundles * bundlePrice + regularQty * salePrice;
                        return {
                          id: entry.id,
                          name: material.name,
                          bundles,
                          minQty,
                          bundlePrice,
                          regularQty,
                          salePrice,
                          total,
                        };
                      })
                      .filter(Boolean)
                      .map((row: any) => (
                        <div key={row.id} className="rounded border border-dashed p-2">
                          <p className="font-medium">{row.name}</p>
                          <p>
                            {t?.previewLine1 ?? 'إذا اشترى العميل'} {previewQuantity} {t?.previewPieces ?? 'قطع'}:
                            {' '}
                            {row.bundles} × ({row.minQty} {t?.forPrice ?? 'بـ'} {formatPrice(row.bundlePrice)})
                            {' + '}
                            {row.regularQty} × {formatPrice(row.salePrice)}
                          </p>
                          <p className="font-semibold">{t?.previewTotal ?? 'الإجمالي'} = {formatPrice(row.total)}</p>
                        </div>
                      ))}
                  </div>
                </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>
          </Tabs>

          <DialogFooter>
            <Button type="button" variant="outline" onClick={() => { setShowCreateDialog(false); resetForm(); }}>
              {tGlobal?.cancel ?? 'إلغاء'}
            </Button>
            <Button type="button" onClick={onCreateOrUpdate} disabled={isPending || hasBlockingRowErrors}>
              {editingCampaignId ? t?.saveChangesButton ?? 'حفظ التعديلات' : t?.createButton ?? 'إنشاء'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </Card>
  );
}
