'use client';

import { useEffect, useMemo, useState, useTransition } from 'react';
import { format } from 'date-fns';
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 { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Textarea } from '@/components/ui/textarea';
import { Eye, PlusCircle, Search, Trash2 } from 'lucide-react';
import { useToast } from '@/hooks/use-toast';
import { handleCreateCoupon, handleUpdateCouponStatus } from '@/lib/actions';
import type { ChartOfAccount, Coupon, Currency, Customer, IncomingCheck, GeneralBank } from '@/lib/types';

type CheckItem = {
  id: string;
  checkNumber: string;
  bankId: string;
  bankName: string;
  checkDate: string;
  currency: string;
  amount: number;
};

type CouponsManagerProps = {
  coupons: Coupon[];
  customers: Customer[];
  banks: GeneralBank[];
  currencies: Currency[];
  defaultCurrency: Currency | null;
  incomingChecks: IncomingCheck[];
  chartOfAccounts: ChartOfAccount[];
  printingSettings?: {
    printHeaderLeftText?: string;
    printHeaderCenterText?: string;
    printHeaderRightText?: string;
    printHeaderText?: string;
    printFooterText?: string;
  };
  t: any;
  tGlobal: any;
};

export default function CouponsManager({
  coupons,
  customers,
  banks,
  currencies,
  defaultCurrency,
  incomingChecks,
  chartOfAccounts,
  printingSettings,
  t,
  tGlobal,
}: CouponsManagerProps) {
  const { toast } = useToast();
  const [isPending, startTransition] = useTransition();
  const [searchQuery, setSearchQuery] = useState('');
  const [statusFilter, setStatusFilter] = useState<string>('_all');
  const [customerTypeFilter, setCustomerTypeFilter] = useState<string>('_all');
  const [paymentMethodFilter, setPaymentMethodFilter] = useState<string>('_all');
  const [showCreateDialog, setShowCreateDialog] = useState(false);
  const [detailsCoupon, setDetailsCoupon] = useState<Coupon | null>(null);
  const [activeCreateTab, setActiveCreateTab] = useState<'general' | 'payment' | 'accounting'>('general');

  const [title, setTitle] = useState('');
  const [amount, setAmount] = useState('');
  const [couponCode, setCouponCode] = useState('');
  const [expiryDate, setExpiryDate] = useState('');
  const [notes, setNotes] = useState('');
  const [couponCurrency, setCouponCurrency] = useState(defaultCurrency?.code || currencies.find((currency) => currency.isDefault)?.code || 'JOD');
  const [customerType, setCustomerType] = useState<'cash' | 'customer'>('cash');
  const [customerId, setCustomerId] = useState('');
  const [paymentMethod, setPaymentMethod] = useState<'cash' | 'check' | 'credit'>('cash');
  const [checks, setChecks] = useState<CheckItem[]>([]);
  const [checkNumber, setCheckNumber] = useState('');
  const [checkBankId, setCheckBankId] = useState('');
  const [checkDate, setCheckDate] = useState(format(new Date(), 'yyyy-MM-dd'));
  const [checkCurrency, setCheckCurrency] = useState(defaultCurrency?.code || currencies.find((currency) => currency.isDefault)?.code || 'JOD');
  const [checkAmount, setCheckAmount] = useState('');

  const resolvedDefaultCurrencyCode = useMemo(
    () => String(currencies.find((currency) => currency.isDefault)?.code || defaultCurrency?.code || 'JOD').trim() || 'JOD',
    [currencies, defaultCurrency],
  );

  useEffect(() => {
    const exists = (currencies || []).some((currency) => String(currency.code || '').trim() === String(couponCurrency || '').trim());
    if (!exists) {
      setCouponCurrency(resolvedDefaultCurrencyCode);
    }
  }, [couponCurrency, currencies, resolvedDefaultCurrencyCode]);

  const banksById = useMemo(
    () => new Map((banks || []).map((bank) => [String(bank.id || '').trim(), bank])),
    [banks],
  );
  const accountsByCode = useMemo(
    () => new Map((chartOfAccounts || []).map((account) => [String(account.code || '').trim(), account])),
    [chartOfAccounts],
  );
  const accountsById = useMemo(
    () => new Map((chartOfAccounts || []).map((account) => [String(account.id || '').trim(), account])),
    [chartOfAccounts],
  );
  const selectedCustomer = useMemo(
    () => customers.find((customer) => customer.id === customerId) || null,
    [customerId, customers],
  );
  const checksTotal = useMemo(
    () => checks.reduce((sum, check) => sum + Number(check.amount || 0), 0),
    [checks],
  );
  const incomingChecksByCouponId = useMemo(() => {
    const map = new Map<string, IncomingCheck[]>();
    (incomingChecks || []).forEach((check) => {
      const notes = String(check.notes || '');
      const match = notes.match(/\[COUPON:([^\]]+)\]/);
      if (!match) return;
      const couponId = String(match[1] || '').trim();
      if (!couponId) return;
      const existing = map.get(couponId) || [];
      existing.push(check);
      map.set(couponId, existing);
    });
    return map;
  }, [incomingChecks]);

  const buildAccountPath = (account?: ChartOfAccount | null) => {
    if (!account) return '';
    const segments: string[] = [];
    let current: ChartOfAccount | undefined | null = account;
    let depth = 0;

    while (current && depth < 8) {
      segments.unshift(`${current.code} - ${current.nameAr || current.nameEn}`);
      current = current.parentId ? accountsById.get(String(current.parentId || '').trim()) : null;
      depth += 1;
    }

    return segments.join(' / ');
  };

  const accountingPreview = useMemo(() => {
    const rows: Array<{ key: string; label: string; account?: ChartOfAccount; fallbackCode: string; fallbackName: string; helper: string }> = [];
    const couponLiability = accountsByCode.get('2135');
    const cashAccount = accountsByCode.get('1110');
    const notesReceivable = accountsByCode.get('1140');
    const customerAccount = selectedCustomer?.accountCode ? accountsByCode.get(String(selectedCustomer.accountCode || '').trim()) : undefined;
    const firstCheckBank = checks.length > 0 ? banksById.get(String(checks[0].bankId || '').trim()) : undefined;
    const firstCheckBankAccount = firstCheckBank?.accountCode
      ? accountsByCode.get(String(firstCheckBank.accountCode || '').trim())
      : undefined;

    rows.push({
      key: 'settlement',
      label: t?.settlementAccountLabel ?? 'حساب التسوية',
      account: paymentMethod === 'credit' ? customerAccount : paymentMethod === 'check' ? notesReceivable : cashAccount,
      fallbackCode: paymentMethod === 'credit' ? (selectedCustomer?.accountCode || '1130') : paymentMethod === 'check' ? '1140' : '1110',
      fallbackName: paymentMethod === 'credit' ? (selectedCustomer?.name || 'العملاء') : paymentMethod === 'check' ? 'أوراق القبض' : 'الصندوق',
      helper: paymentMethod === 'credit'
        ? (t?.creditSettlementHint ?? 'يُثبت الكوبون على ذمة الزبون العادي.')
        : paymentMethod === 'check'
          ? (t?.checkSettlementHint ?? 'تُرحل قيمة الكوبون إلى أوراق القبض مع تسجيل الشيكات الواردة.')
          : (t?.cashSettlementHint ?? 'تُرحل قيمة الكوبون مباشرة إلى الصندوق.'),
    });
    rows.push({
      key: 'liability',
      label: t?.couponLiabilityLabel ?? 'حساب التزام الكوبونات',
      account: couponLiability,
      fallbackCode: '2135',
      fallbackName: 'التزامات الكوبونات المدفوعة مسبقاً',
      helper: t?.couponLiabilityHint ?? 'يمثل الرصيد غير المستخدم من الكوبونات المباعة.',
    });

    if (customerType === 'customer') {
      rows.push({
        key: 'customer',
        label: t?.customerAccountLabel ?? 'حساب الزبون',
        account: customerAccount,
        fallbackCode: selectedCustomer?.accountCode || '1130',
        fallbackName: selectedCustomer?.name || 'العملاء',
        helper: t?.customerAccountHint ?? 'الحساب المرتبط بالزبون ضمن شجرة العملاء.',
      });
    }

    if (paymentMethod === 'check' && firstCheckBank) {
      rows.push({
        key: 'check-bank',
        label: t?.referenceBankAccountLabel ?? 'بنك الشيك المرجعي',
        account: firstCheckBankAccount,
        fallbackCode: String(firstCheckBank.accountCode || ''),
        fallbackName: String(firstCheckBank.name || 'بنك الشيك'),
        helper: t?.referenceBankAccountHint ?? 'يُعرض البنك المرجعي لأول شيك مدخل داخل النموذج.',
      });
    }

    return rows;
  }, [accountsByCode, banksById, checks, customerType, paymentMethod, selectedCustomer, t]);

  const filteredCoupons = useMemo(() => {
    const query = String(searchQuery || '').trim().toLowerCase();
    return [...(coupons || [])]
      .filter((coupon) => {
        if (statusFilter !== '_all' && coupon.status !== statusFilter) return false;
        if (customerTypeFilter !== '_all' && (coupon.customerType || 'cash') !== customerTypeFilter) return false;
        if (paymentMethodFilter !== '_all' && (coupon.paymentMethod || 'cash') !== paymentMethodFilter) return false;
        if (!query) return true;
        const fields = [
          coupon.couponNumber,
          coupon.couponCode,
          coupon.title,
          coupon.customerName,
          coupon.customerType,
          coupon.paymentMethod,
          coupon.notes,
          coupon.status,
        ]
          .map((value) => String(value || '').toLowerCase())
          .join(' ');
        return fields.includes(query);
      })
      .sort((a, b) => new Date(b.createdAt || 0).getTime() - new Date(a.createdAt || 0).getTime());
  }, [coupons, customerTypeFilter, paymentMethodFilter, searchQuery, statusFilter]);

  const paymentMethodTotals = useMemo(() => {
    const totals = {
      cash: { amount: 0, remaining: 0, count: 0 },
      check: { amount: 0, remaining: 0, count: 0 },
      credit: { amount: 0, remaining: 0, count: 0 },
      all: { amount: 0, remaining: 0, count: 0 },
    };

    filteredCoupons.forEach((coupon) => {
      const method = (coupon.paymentMethod || 'cash') as 'cash' | 'check' | 'credit';
      const originalAmount = Number(coupon.originalAmount || 0);
      const remainingAmount = Number(coupon.remainingAmount || 0);
      totals[method].amount += originalAmount;
      totals[method].remaining += remainingAmount;
      totals[method].count += 1;
      totals.all.amount += originalAmount;
      totals.all.remaining += remainingAmount;
      totals.all.count += 1;
    });

    return totals;
  }, [filteredCoupons]);

  const resetCreateForm = () => {
    setTitle('');
    setAmount('');
    setCouponCode('');
    setExpiryDate('');
    setNotes('');
    setCouponCurrency(resolvedDefaultCurrencyCode);
    setCustomerType('cash');
    setCustomerId('');
    setPaymentMethod('cash');
    setChecks([]);
    setCheckNumber('');
    setCheckBankId('');
    setCheckDate(format(new Date(), 'yyyy-MM-dd'));
    setCheckCurrency(resolvedDefaultCurrencyCode);
    setCheckAmount('');
    setActiveCreateTab('general');
  };

  const handleAddCheck = () => {
    const normalizedNumber = String(checkNumber || '').trim();
    const normalizedBankId = String(checkBankId || '').trim();
    const normalizedDate = String(checkDate || '').trim();
    const normalizedCurrency = String(checkCurrency || '').trim();
    const numericAmount = Number(checkAmount || 0);
    const bank = banksById.get(normalizedBankId);

    if (!normalizedNumber || !normalizedBankId || !normalizedDate || !normalizedCurrency || numericAmount <= 0) {
      toast({
        title: tGlobal?.error ?? 'خطأ',
        description: t?.invalidCheckData ?? 'يرجى إدخال جميع بيانات الشيك بشكل صحيح.',
        variant: 'destructive',
      });
      return;
    }

    setChecks((current) => [
      ...current,
      {
        id: `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
        checkNumber: normalizedNumber,
        bankId: normalizedBankId,
        bankName: String(bank?.name || '').trim(),
        checkDate: normalizedDate,
        currency: normalizedCurrency,
        amount: numericAmount,
      },
    ]);
    setCheckNumber('');
    setCheckBankId('');
    setCheckDate(format(new Date(), 'yyyy-MM-dd'));
    setCheckCurrency(resolvedDefaultCurrencyCode);
    setCheckAmount('');
  };

  const handleRemoveCheck = (id: string) => {
    setChecks((current) => current.filter((check) => check.id !== id));
  };

  const onCreate = () => {
    const numericAmount = Number(amount || 0);
    if (!title.trim()) {
      toast({ title: tGlobal?.error ?? 'خطأ', description: t?.titleRequired ?? 'عنوان الكوبون مطلوب', variant: 'destructive' });
      return;
    }
    if (numericAmount <= 0) {
      toast({ title: tGlobal?.error ?? 'خطأ', description: t?.amountRequired ?? 'قيمة الكوبون يجب أن تكون أكبر من صفر', variant: 'destructive' });
      return;
    }

    if (customerType === 'customer' && !customerId) {
      toast({ title: tGlobal?.error ?? 'خطأ', description: t?.customerRequired ?? 'يرجى اختيار الزبون.', variant: 'destructive' });
      return;
    }

    if (paymentMethod === 'credit' && customerType !== 'customer') {
      toast({ title: tGlobal?.error ?? 'خطأ', description: t?.creditCustomerRequired ?? 'الدفع الآجل يحتاج زبوناً عادياً.', variant: 'destructive' });
      return;
    }

    if (paymentMethod === 'check') {
      if (checks.length === 0) {
        toast({ title: tGlobal?.error ?? 'خطأ', description: t?.checkRequired ?? 'يجب إضافة شيك واحد على الأقل.', variant: 'destructive' });
        return;
      }

      if (Math.abs(checksTotal - numericAmount) > 0.0001) {
        toast({ title: tGlobal?.error ?? 'خطأ', description: t?.checkTotalMismatch ?? 'مجموع الشيكات يجب أن يساوي قيمة الكوبون.', variant: 'destructive' });
        return;
      }
    }

    startTransition(async () => {
      const result = await handleCreateCoupon({
        title: title.trim(),
        amount: numericAmount,
        couponCode: couponCode.trim(),
        currencyCode: String(couponCurrency || '').trim() || resolvedDefaultCurrencyCode,
        customerType,
        customerId: customerType === 'customer' ? customerId : '',
        paymentMethod,
        checks,
        expiryDate: expiryDate.trim(),
        notes: notes.trim(),
      });

      if ((result as any)?.success) {
        toast({ title: t?.couponCreated ?? 'تم إنشاء الكوبون', description: (result as any)?.coupon?.couponNumber || '' });
        setShowCreateDialog(false);
        resetCreateForm();
      } else {
        toast({
          title: tGlobal?.error ?? 'خطأ',
          description: String((result as any)?.error || t?.createFailed || 'تعذر إنشاء الكوبون'),
          variant: 'destructive',
        });
      }
    });
  };

  const onStatusChange = (couponId: string, status: Coupon['status']) => {
    startTransition(async () => {
      const result = await handleUpdateCouponStatus({ couponId, status });
      if ((result as any)?.success) {
        toast({ title: t?.statusUpdated ?? 'تم تحديث الحالة' });
      } else {
        toast({
          title: tGlobal?.error ?? 'خطأ',
          description: String((result as any)?.error || t?.statusUpdateFailed || 'تعذر تحديث حالة الكوبون'),
          variant: 'destructive',
        });
      }
    });
  };

  const statusLabel = (status: Coupon['status']) => {
    if (status === 'active') return t?.statusActive ?? 'نشط';
    if (status === 'used') return t?.statusUsed ?? 'مستخدم';
    if (status === 'expired') return t?.statusExpired ?? 'منتهي';
    if (status === 'cancelled') return t?.statusCancelled ?? 'ملغي';
    return status;
  };

  const customerTypeLabel = (value?: Coupon['customerType'] | 'cash' | 'customer') => {
    return value === 'customer' ? (t?.regularCustomer ?? 'زبون عادي') : (t?.cashCustomer ?? 'زبون نقدي');
  };

  const paymentMethodLabel = (value?: Coupon['paymentMethod'] | 'cash' | 'check' | 'credit') => {
    if (value === 'check') return t?.check ?? 'شيكات';
    if (value === 'credit') return t?.credit ?? 'آجل';
    return t?.cash ?? 'نقداً';
  };

  const getAccountDisplay = (code?: string, fallbackName?: string) => {
    const normalizedCode = String(code || '').trim();
    const account = normalizedCode ? accountsByCode.get(normalizedCode) : undefined;
    return {
      code: normalizedCode || '-',
      name: String(account?.nameAr || account?.nameEn || fallbackName || '-'),
      path: account ? buildAccountPath(account) : '',
    };
  };

  const formatAmountWithCurrency = (amount: number, currency?: string) => {
    const code = String(currency || '').trim();
    return `${Number(amount || 0).toFixed(2)}${code ? ` ${code}` : ''}`;
  };

  const escapeHtml = (value: string) => String(value || '')
    .replaceAll('&', '&amp;')
    .replaceAll('<', '&lt;')
    .replaceAll('>', '&gt;')
    .replaceAll('"', '&quot;')
    .replaceAll("'", '&#39;');

  const printMultilineHtml = (value: string) => String(value || '')
    .split(/\r?\n/)
    .map((line) => line.trim())
    .filter(Boolean)
    .map((line) => escapeHtml(line))
    .join('<br/>');

  const handlePrintCouponDetails = (coupon: Coupon) => {
    const popup = window.open('', '_blank', 'noopener,noreferrer,width=960,height=720');
    if (!popup) {
      toast({
        title: tGlobal?.error ?? 'خطأ',
        description: t?.printWindowBlocked ?? 'تعذر فتح نافذة الطباعة. تحقق من إعدادات المتصفح.',
        variant: 'destructive',
      });
      return;
    }

    const relatedChecks = incomingChecksByCouponId.get(coupon.id) || [];
    const headerText = String(printingSettings?.printHeaderText || '').trim();
    const headerLeftText = String(printingSettings?.printHeaderLeftText || '').trim();
    const headerCenterText = String(printingSettings?.printHeaderCenterText || '').trim();
    const headerRightText = String(printingSettings?.printHeaderRightText || '').trim();
    const footerText = String(printingSettings?.printFooterText || '').trim();
    const hasSplitHeader = Boolean(headerLeftText || headerCenterText || headerRightText);
    const headerBlock = hasSplitHeader
      ? `<div class="custom-print-header-grid"><div class="custom-print-header-cell">${printMultilineHtml(headerRightText)}</div><div class="custom-print-header-cell center">${printMultilineHtml(headerCenterText)}</div><div class="custom-print-header-cell left">${printMultilineHtml(headerLeftText)}</div></div>`
      : (headerText ? `<div class="custom-print-header">${printMultilineHtml(headerText)}</div>` : '');
    const footerBlock = footerText ? `<div class="custom-print-footer">${printMultilineHtml(footerText)}</div>` : '';
    const settlementAccount = getAccountDisplay(coupon.settlementAccountCode, coupon.settlementAccountName);
    const liabilityAccount = getAccountDisplay(coupon.liabilityAccountCode, coupon.liabilityAccountName);
    const customerAccount = getAccountDisplay(coupon.customerAccountCode, coupon.customerName || (t?.customerAccountLabel ?? 'حساب الزبون'));
    const checksRows = relatedChecks.length === 0
      ? `<tr><td colspan="6" style="padding:12px;text-align:center;color:#6b7280;">${escapeHtml(t?.noLinkedChecks ?? 'لا توجد شيكات مرتبطة بهذا الكوبون.')}</td></tr>`
      : relatedChecks
          .map((check) => `
            <tr>
              <td style="padding:10px;border-bottom:1px solid #e5e7eb;">${escapeHtml(String(check.checkNumber || '-'))}</td>
              <td style="padding:10px;border-bottom:1px solid #e5e7eb;">${escapeHtml(String(check.bankName || '-'))}</td>
              <td style="padding:10px;border-bottom:1px solid #e5e7eb;">${escapeHtml(check.checkDate ? formatDateStable(check.checkDate) : '-')}</td>
              <td style="padding:10px;border-bottom:1px solid #e5e7eb;">${escapeHtml(String(check.currency || '-'))}</td>
              <td style="padding:10px;border-bottom:1px solid #e5e7eb;text-align:right;">${Number(check.amount || 0).toFixed(2)}</td>
              <td style="padding:10px;border-bottom:1px solid #e5e7eb;">${escapeHtml(String(check.status || '-'))}</td>
            </tr>`)
          .join('');

    popup.document.write(`<!doctype html>
<html lang="ar" dir="rtl">
  <head>
    <meta charset="utf-8" />
    <title>${escapeHtml(coupon.couponNumber || (t?.couponDetailsTitle ?? 'تفاصيل الكوبون'))}</title>
    <style>
      body { font-family: Tahoma, Arial, sans-serif; margin: 24px; color: #111827; }
      h1, h2 { margin: 0 0 12px; }
      .meta { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px; margin-bottom: 18px; }
      .card { border: 1px solid #d1d5db; border-radius: 8px; padding: 12px; }
      .label { color: #6b7280; font-size: 12px; margin-bottom: 6px; }
      .value { font-size: 14px; font-weight: 600; }
      .section { margin-top: 18px; }
      table { width: 100%; border-collapse: collapse; margin-top: 12px; }
      th { text-align: right; background: #f3f4f6; padding: 10px; font-size: 12px; }
      td { font-size: 13px; }
      .note { white-space: pre-wrap; border: 1px solid #d1d5db; border-radius: 8px; padding: 12px; margin-top: 12px; }
      .custom-print-header { text-align: center; border: 1px solid #e5e7eb; background: #f8fafc; border-radius: 8px; padding: 8px; margin-bottom: 10px; font-size: 12px; line-height: 1.6; font-weight: 600; }
      .custom-print-header-grid { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 8px; border: 1px solid #e5e7eb; background: #f8fafc; border-radius: 8px; padding: 8px; margin-bottom: 10px; }
      .custom-print-header-cell { min-height: 34px; padding: 6px; border: 1px solid #e5e7eb; border-radius: 6px; background: #ffffff; font-size: 11px; line-height: 1.5; text-align: right; white-space: pre-wrap; }
      .custom-print-header-cell.center { text-align: center; }
      .custom-print-header-cell.left { text-align: left; }
      .custom-print-footer { text-align: center; border-top: 1px dashed #d1d5db; margin-top: 14px; padding-top: 8px; font-size: 11px; color: #374151; line-height: 1.5; }
    </style>
  </head>
  <body>
    ${headerBlock}
    <h1>${escapeHtml(t?.couponDetailsTitle ?? 'تفاصيل الكوبون')}</h1>
    <p>${escapeHtml(coupon.couponNumber || '-')}</p>

    <div class="meta">
      <div class="card"><div class="label">${escapeHtml(t?.titleLabel ?? 'العنوان')}</div><div class="value">${escapeHtml(coupon.title || '-')}</div></div>
      <div class="card"><div class="label">${escapeHtml(t?.customerLabel ?? 'الزبون')}</div><div class="value">${escapeHtml(coupon.customerName || customerTypeLabel(coupon.customerType))}</div></div>
      <div class="card"><div class="label">${escapeHtml(t?.paymentMethod ?? 'آلية السداد')}</div><div class="value">${escapeHtml(paymentMethodLabel(coupon.paymentMethod))}</div></div>
      <div class="card"><div class="label">${escapeHtml(t?.statusLabel ?? 'الحالة')}</div><div class="value">${escapeHtml(statusLabel(coupon.status))}</div></div>
    </div>

    <div class="section">
      <h2>${escapeHtml(t?.accountingTab ?? 'المحاسبة')}</h2>
      <div class="meta">
        <div class="card"><div class="label">${escapeHtml(t?.settlementAccountLabel ?? 'حساب التسوية')}</div><div class="value">${escapeHtml(`${settlementAccount.code} - ${settlementAccount.name}`)}</div><div class="label">${escapeHtml(settlementAccount.path || '-')}</div></div>
        <div class="card"><div class="label">${escapeHtml(t?.couponLiabilityLabel ?? 'حساب التزام الكوبونات')}</div><div class="value">${escapeHtml(`${liabilityAccount.code} - ${liabilityAccount.name}`)}</div><div class="label">${escapeHtml(liabilityAccount.path || '-')}</div></div>
        <div class="card"><div class="label">${escapeHtml(t?.customerAccountLabel ?? 'حساب الزبون')}</div><div class="value">${escapeHtml(`${customerAccount.code} - ${customerAccount.name}`)}</div><div class="label">${escapeHtml(customerAccount.path || '-')}</div></div>
      </div>
    </div>

    <div class="section">
      <h2>${escapeHtml(t?.linkedChecksTitle ?? 'الشيكات المرتبطة')}</h2>
      <table>
        <thead>
          <tr>
            <th>${escapeHtml(t?.checkNumber ?? 'رقم الشيك')}</th>
            <th>${escapeHtml(t?.bank ?? 'البنك')}</th>
            <th>${escapeHtml(t?.checkDate ?? 'تاريخ الشيك')}</th>
            <th>${escapeHtml(t?.currencyLabel ?? 'العملة')}</th>
            <th>${escapeHtml(t?.amountLabel ?? 'القيمة')}</th>
            <th>${escapeHtml(t?.statusLabel ?? 'الحالة')}</th>
          </tr>
        </thead>
        <tbody>${checksRows}</tbody>
      </table>
    </div>

    ${coupon.notes ? `<div class="section"><h2>${escapeHtml(t?.notesLabel ?? 'ملاحظات')}</h2><div class="note">${escapeHtml(coupon.notes)}</div></div>` : ''}
    ${footerBlock}
  </body>
</html>`);
    popup.document.close();
    popup.focus();
    popup.print();
  };

  const statusVariant = (status: Coupon['status']) => {
    if (status === 'active') return 'default';
    if (status === 'used') return 'secondary';
    if (status === 'expired') return 'outline';
    if (status === 'cancelled') return 'destructive';
    return 'outline';
  };

  return (
    <Card>
      <CardHeader>
        <CardTitle>{t?.title ?? 'إدارة الكوبونات'}</CardTitle>
        <CardDescription>{t?.description ?? 'إدارة قسائم شراء مدفوعة مسبقاً مع رصيد متبقي واستحقاق'}</CardDescription>
      </CardHeader>
      <CardContent className="space-y-4">
        <div className="flex flex-wrap gap-3">
          <Button size="sm" onClick={() => setShowCreateDialog(true)}>
            <PlusCircle className="me-2 h-4 w-4" />
            {t?.createButton ?? 'إنشاء كوبون'}
          </Button>
        </div>

        <div className="grid grid-cols-1 gap-3 md:grid-cols-2 xl:grid-cols-4">
          <div className="space-y-1 rounded-md border bg-muted/20 p-3">
            <Label>{t?.searchLabel ?? 'بحث'}</Label>
            <div className="relative">
              <Search className="absolute right-2 top-2.5 h-4 w-4 text-muted-foreground" />
              <Input
                value={searchQuery}
                onChange={(event) => setSearchQuery(event.target.value)}
                placeholder={t?.searchPlaceholder ?? 'رقم مرجعي، كود الكوبون، العنوان...'}
                className="pe-8"
              />
            </div>
          </div>

          <div className="space-y-1 rounded-md border bg-muted/20 p-3">
            <Label>{t?.statusFilterLabel ?? 'تصفية حسب الحالة'}</Label>
            <Select value={statusFilter} onValueChange={setStatusFilter}>
              <SelectTrigger>
                <SelectValue placeholder={t?.allStatuses ?? 'كل الحالات'} />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="_all">{t?.allStatuses ?? 'كل الحالات'}</SelectItem>
                <SelectItem value="active">{statusLabel('active')}</SelectItem>
                <SelectItem value="used">{statusLabel('used')}</SelectItem>
                <SelectItem value="expired">{statusLabel('expired')}</SelectItem>
                <SelectItem value="cancelled">{statusLabel('cancelled')}</SelectItem>
              </SelectContent>
            </Select>
          </div>

          <div className="space-y-1 rounded-md border bg-muted/20 p-3">
            <Label>{t?.customerTypeFilterLabel ?? 'تصفية حسب نوع الزبون'}</Label>
            <Select value={customerTypeFilter} onValueChange={setCustomerTypeFilter}>
              <SelectTrigger>
                <SelectValue placeholder={t?.allCustomerTypes ?? 'كل أنواع الزبائن'} />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="_all">{t?.allCustomerTypes ?? 'كل أنواع الزبائن'}</SelectItem>
                <SelectItem value="cash">{t?.cashCustomer ?? 'زبون نقدي'}</SelectItem>
                <SelectItem value="customer">{t?.regularCustomer ?? 'زبون عادي'}</SelectItem>
              </SelectContent>
            </Select>
          </div>

          <div className="space-y-1 rounded-md border bg-muted/20 p-3">
            <Label>{t?.paymentMethodFilterLabel ?? 'تصفية حسب آلية السداد'}</Label>
            <Select value={paymentMethodFilter} onValueChange={setPaymentMethodFilter}>
              <SelectTrigger>
                <SelectValue placeholder={t?.allPaymentMethods ?? 'كل طرق السداد'} />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="_all">{t?.allPaymentMethods ?? 'كل طرق السداد'}</SelectItem>
                <SelectItem value="cash">{t?.cash ?? 'نقداً'}</SelectItem>
                <SelectItem value="check">{t?.check ?? 'شيكات'}</SelectItem>
                <SelectItem value="credit">{t?.credit ?? 'آجل'}</SelectItem>
              </SelectContent>
            </Select>
          </div>
        </div>

        <div className="flex items-center justify-between rounded-md border bg-muted/10 px-3 py-2 text-sm text-muted-foreground">
          <span>{t?.resultsCountLabel ?? 'عدد النتائج'}</span>
          <span className="font-mono">{filteredCoupons.length}</span>
        </div>

        <div className="grid grid-cols-1 gap-3 md:grid-cols-2 xl:grid-cols-4">
          <div className="rounded-md border bg-muted/20 p-3">
            <p className="text-xs text-muted-foreground">{t?.paymentTotalsCashLabel ?? 'إجمالي الكوبونات نقداً'}</p>
            <p className="mt-1 text-lg font-semibold font-mono">{paymentMethodTotals.cash.amount.toFixed(2)}</p>
            <p className="text-xs text-muted-foreground">
              {(t?.remainingAmountLabel ?? 'الرصيد المتبقي')}: {paymentMethodTotals.cash.remaining.toFixed(2)} - {paymentMethodTotals.cash.count} {t?.recordsLabel ?? 'سجل'}
            </p>
          </div>

          <div className="rounded-md border bg-muted/20 p-3">
            <p className="text-xs text-muted-foreground">{t?.paymentTotalsCheckLabel ?? 'إجمالي الكوبونات بالشيكات'}</p>
            <p className="mt-1 text-lg font-semibold font-mono">{paymentMethodTotals.check.amount.toFixed(2)}</p>
            <p className="text-xs text-muted-foreground">
              {(t?.remainingAmountLabel ?? 'الرصيد المتبقي')}: {paymentMethodTotals.check.remaining.toFixed(2)} - {paymentMethodTotals.check.count} {t?.recordsLabel ?? 'سجل'}
            </p>
          </div>

          <div className="rounded-md border bg-muted/20 p-3">
            <p className="text-xs text-muted-foreground">{t?.paymentTotalsCreditLabel ?? 'إجمالي الكوبونات الآجلة'}</p>
            <p className="mt-1 text-lg font-semibold font-mono">{paymentMethodTotals.credit.amount.toFixed(2)}</p>
            <p className="text-xs text-muted-foreground">
              {(t?.remainingAmountLabel ?? 'الرصيد المتبقي')}: {paymentMethodTotals.credit.remaining.toFixed(2)} - {paymentMethodTotals.credit.count} {t?.recordsLabel ?? 'سجل'}
            </p>
          </div>

          <div className="rounded-md border bg-muted/20 p-3">
            <p className="text-xs text-muted-foreground">{t?.paymentTotalsAllLabel ?? 'الإجمالي الكلي'}</p>
            <p className="mt-1 text-lg font-semibold font-mono">{paymentMethodTotals.all.amount.toFixed(2)}</p>
            <p className="text-xs text-muted-foreground">
              {(t?.remainingAmountLabel ?? 'الرصيد المتبقي')}: {paymentMethodTotals.all.remaining.toFixed(2)} - {paymentMethodTotals.all.count} {t?.recordsLabel ?? 'سجل'}
            </p>
          </div>
        </div>

        <div className="rounded-md border overflow-x-auto">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>{t?.referenceLabel ?? 'المرجع'}</TableHead>
                <TableHead>{t?.codeLabel ?? 'كود الكوبون'}</TableHead>
                <TableHead>{t?.titleLabel ?? 'العنوان'}</TableHead>
                <TableHead>{t?.customerColumnLabel ?? 'الزبون'}</TableHead>
                <TableHead>{t?.paymentMethod ?? 'آلية السداد'}</TableHead>
                <TableHead className="text-right">{t?.originalAmountLabel ?? 'القيمة الأصلية'}</TableHead>
                <TableHead className="text-right">{t?.remainingAmountLabel ?? 'الرصيد المتبقي'}</TableHead>
                <TableHead>{t?.statusLabel ?? 'الحالة'}</TableHead>
                <TableHead>{t?.expiryDateLabel ?? 'تاريخ الانتهاء'}</TableHead>
                <TableHead>{t?.createdAtLabel ?? 'تاريخ الإنشاء'}</TableHead>
                <TableHead>{t?.actionsLabel ?? 'إجراءات'}</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {filteredCoupons.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={11} className="h-24 text-center text-muted-foreground">
                    {t?.noCoupons ?? 'لا توجد كوبونات'}
                  </TableCell>
                </TableRow>
              ) : (
                filteredCoupons.map((coupon) => (
                  <TableRow key={coupon.id}>
                    <TableCell className="font-mono text-xs">{coupon.couponNumber}</TableCell>
                    <TableCell className="font-mono text-xs">{coupon.couponCode}</TableCell>
                    <TableCell>{coupon.title}</TableCell>
                    <TableCell>
                      <div className="space-y-1">
                        <div>{coupon.customerType === 'customer' ? (coupon.customerName || '-') : (t?.cashCustomer ?? 'زبون نقدي')}</div>
                        <div className="text-xs text-muted-foreground">{customerTypeLabel(coupon.customerType)}</div>
                      </div>
                    </TableCell>
                    <TableCell>
                      <div className="space-y-1">
                        <div>{paymentMethodLabel(coupon.paymentMethod)}</div>
                        {coupon.settlementAccountCode ? (
                          <div className="text-xs text-muted-foreground">{coupon.settlementAccountCode}</div>
                        ) : null}
                      </div>
                    </TableCell>
                    <TableCell className="text-right font-mono">{formatAmountWithCurrency(Number(coupon.originalAmount || 0), coupon.currencyCode)}</TableCell>
                    <TableCell className="text-right font-mono">{formatAmountWithCurrency(Number(coupon.remainingAmount || 0), coupon.currencyCode)}</TableCell>
                    <TableCell>
                      <Badge variant={statusVariant(coupon.status)}>{statusLabel(coupon.status)}</Badge>
                    </TableCell>
                    <TableCell>{coupon.expiryDate ? formatDateStable(coupon.expiryDate) : '-'}</TableCell>
                    <TableCell>{formatDateStable(coupon.createdAt)}</TableCell>
                    <TableCell>
                      <div className="flex flex-col gap-2 md:flex-row">
                        <Button type="button" variant="outline" size="sm" onClick={() => setDetailsCoupon(coupon)}>
                          <Eye className="me-2 h-4 w-4" />
                          {t?.detailsButton ?? 'تفاصيل'}
                        </Button>
                        <Select
                          value={coupon.status}
                          onValueChange={(value) => onStatusChange(coupon.id, value as Coupon['status'])}
                          disabled={isPending}
                        >
                          <SelectTrigger className="h-8 w-[130px]">
                            <SelectValue />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value="active">{statusLabel('active')}</SelectItem>
                            <SelectItem value="used">{statusLabel('used')}</SelectItem>
                            <SelectItem value="expired">{statusLabel('expired')}</SelectItem>
                            <SelectItem value="cancelled">{statusLabel('cancelled')}</SelectItem>
                          </SelectContent>
                        </Select>
                      </div>
                    </TableCell>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>
        </div>
      </CardContent>

      <Dialog
        open={showCreateDialog}
        onOpenChange={(open) => {
          setShowCreateDialog(open);
          if (!open) resetCreateForm();
        }}
      >
        <DialogContent className="w-[calc(100vw-1rem)] max-w-5xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>{t?.createTitle ?? 'إنشاء كوبون مدفوع مسبقاً'}</DialogTitle>
            <DialogDescription>{t?.createDescription ?? 'سيتم إنشاء الرقم المرجعي تلقائياً مع ضمان عدم التكرار.'}</DialogDescription>
          </DialogHeader>

          <Tabs value={activeCreateTab} onValueChange={(value) => setActiveCreateTab(value as 'general' | 'payment' | 'accounting')} className="space-y-4">
            <TabsList className="grid w-full grid-cols-1 sm:grid-cols-3 h-auto gap-1">
              <TabsTrigger value="general">{t?.generalTab ?? 'البيانات العامة'}</TabsTrigger>
              <TabsTrigger value="payment">{t?.paymentTab ?? 'السداد والقبض'}</TabsTrigger>
              <TabsTrigger value="accounting">{t?.accountingTab ?? 'المحاسبة'}</TabsTrigger>
            </TabsList>

            <TabsContent value="general" 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 md:col-span-2">
                  <Label>{t?.titleLabel ?? 'العنوان'}</Label>
                  <Input value={title} onChange={(event) => setTitle(event.target.value)} placeholder={t?.titlePlaceholder ?? 'مثال: كوبون هدية رمضان'} />
                </div>
                <div className="space-y-1 rounded-md border bg-muted/20 p-3">
                  <Label>{t?.amountLabel ?? 'القيمة'}</Label>
                  <Input type="number" step="0.01" value={amount} onChange={(event) => setAmount(event.target.value)} placeholder="0.00" />
                </div>
                <div className="space-y-1 rounded-md border bg-muted/20 p-3">
                  <Label>{t?.couponCodeLabel ?? 'كود الكوبون (اختياري)'}</Label>
                  <Input value={couponCode} onChange={(event) => setCouponCode(event.target.value)} placeholder={t?.couponCodePlaceholder ?? 'يُولد تلقائياً إذا تركته فارغاً'} />
                </div>
                <div className="space-y-1 rounded-md border bg-muted/20 p-3">
                  <Label>{t?.expiryDateLabel ?? 'تاريخ الانتهاء (اختياري)'}</Label>
                  <Input type="date" value={expiryDate} onChange={(event) => setExpiryDate(event.target.value)} />
                </div>
                <div className="space-y-1 rounded-md border bg-muted/20 p-3">
                  <Label>{t?.currencyLabel ?? 'العملة'}</Label>
                  <Select value={couponCurrency} onValueChange={setCouponCurrency}>
                    <SelectTrigger>
                      <SelectValue placeholder={t?.currencyLabel ?? 'العملة'} />
                    </SelectTrigger>
                    <SelectContent>
                      {(currencies || []).map((currency) => (
                        <SelectItem key={currency.id} value={currency.code}>
                          {currency.code} - {currency.name || currency.nameEn || currency.code}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
                <div className="space-y-1 rounded-md border bg-muted/20 p-3 md:col-span-2">
                  <Label>{t?.notesLabel ?? 'ملاحظات'}</Label>
                  <Textarea value={notes} onChange={(event) => setNotes(event.target.value)} placeholder={t?.notesPlaceholder ?? 'ملاحظات إضافية'} rows={4} />
                </div>
              </div>
            </TabsContent>

            <TabsContent value="payment" 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?.customerTypeLabel ?? 'نوع الزبون'}</Label>
                  <Select
                    value={customerType}
                    onValueChange={(value) => {
                      const nextType = value as 'cash' | 'customer';
                      setCustomerType(nextType);
                      if (nextType === 'cash') {
                        setCustomerId('');
                        if (paymentMethod === 'credit') setPaymentMethod('cash');
                      }
                    }}
                  >
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="cash">{t?.cashCustomer ?? 'زبون نقدي'}</SelectItem>
                      <SelectItem value="customer">{t?.regularCustomer ?? 'زبون عادي'}</SelectItem>
                    </SelectContent>
                  </Select>
                </div>

                <div className="space-y-1 rounded-md border bg-muted/20 p-3">
                  <Label>{t?.paymentMethod ?? 'آلية السداد'}</Label>
                  <Select value={paymentMethod} onValueChange={(value) => setPaymentMethod(value as 'cash' | 'check' | 'credit')}>
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="cash">{t?.cash ?? 'نقداً'}</SelectItem>
                      <SelectItem value="check">{t?.check ?? 'شيكات'}</SelectItem>
                      {customerType === 'customer' ? <SelectItem value="credit">{t?.credit ?? 'آجل'}</SelectItem> : null}
                    </SelectContent>
                  </Select>
                </div>

                {customerType === 'customer' ? (
                  <div className="space-y-1 rounded-md border bg-muted/20 p-3 md:col-span-2">
                    <Label>{t?.customerLabel ?? 'الزبون'}</Label>
                    <Select value={customerId} onValueChange={setCustomerId}>
                      <SelectTrigger>
                        <SelectValue placeholder={t?.customerSelectPlaceholder ?? 'اختر الزبون'} />
                      </SelectTrigger>
                      <SelectContent>
                        {(customers || []).map((customer) => (
                          <SelectItem key={customer.id} value={customer.id}>
                            {customer.name}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>
                ) : null}
              </div>

              {paymentMethod === 'check' ? (
                <div className="space-y-3 rounded-md border bg-muted/10 p-4">
                  <div className="flex items-center justify-between gap-3">
                    <div>
                      <p className="font-medium">{t?.checksSectionTitle ?? 'الشيكات المقبوضة مقابل الكوبون'}</p>
                      <p className="text-sm text-muted-foreground">{t?.checksSectionDescription ?? 'أدخل الشيكات بالطريقة نفسها المتبعة في سند القبض.'}</p>
                    </div>
                    <Badge variant="outline">{checks.length} {t?.checksCountLabel ?? 'شيك'}</Badge>
                  </div>

                  <div className="grid gap-3 md:grid-cols-5">
                    <div className="space-y-1 md:col-span-2">
                      <Label>{t?.checkNumber ?? 'رقم الشيك'}</Label>
                      <Input value={checkNumber} onChange={(event) => setCheckNumber(event.target.value)} />
                    </div>
                    <div className="space-y-1 md:col-span-2">
                      <Label>{t?.bank ?? 'البنك'}</Label>
                      <Select value={checkBankId} onValueChange={setCheckBankId}>
                        <SelectTrigger>
                          <SelectValue placeholder={t?.selectBank ?? 'اختر البنك'} />
                        </SelectTrigger>
                        <SelectContent>
                          {(banks || []).map((bank) => (
                            <SelectItem key={bank.id} value={bank.id}>
                              {bank.name}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>
                    <div className="space-y-1">
                      <Label>{t?.checkDate ?? 'تاريخ الشيك'}</Label>
                      <Input type="date" value={checkDate} onChange={(event) => setCheckDate(event.target.value)} />
                    </div>
                    <div className="space-y-1">
                      <Label>{t?.currencyLabel ?? 'العملة'}</Label>
                      <Select value={checkCurrency} onValueChange={setCheckCurrency}>
                        <SelectTrigger>
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          {(currencies || []).map((currency) => (
                            <SelectItem key={currency.id} value={currency.code}>
                              {currency.code}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>
                    <div className="space-y-1">
                      <Label>{t?.amountLabel ?? 'القيمة'}</Label>
                      <Input type="number" step="0.01" value={checkAmount} onChange={(event) => setCheckAmount(event.target.value)} />
                    </div>
                  </div>

                  <div className="flex justify-end">
                    <Button type="button" variant="outline" onClick={handleAddCheck}>
                      <PlusCircle className="me-2 h-4 w-4" />
                      {t?.addCheck ?? 'إضافة شيك'}
                    </Button>
                  </div>

                  <div className="rounded-md border bg-background overflow-x-auto">
                    <Table>
                      <TableHeader>
                        <TableRow>
                          <TableHead>{t?.checkNumber ?? 'رقم الشيك'}</TableHead>
                          <TableHead>{t?.bank ?? 'البنك'}</TableHead>
                          <TableHead>{t?.checkDate ?? 'تاريخ الشيك'}</TableHead>
                          <TableHead>{t?.currencyLabel ?? 'العملة'}</TableHead>
                          <TableHead className="text-right">{t?.amountLabel ?? 'القيمة'}</TableHead>
                          <TableHead>{t?.actionsLabel ?? 'إجراءات'}</TableHead>
                        </TableRow>
                      </TableHeader>
                      <TableBody>
                        {checks.length === 0 ? (
                          <TableRow>
                            <TableCell colSpan={6} className="h-20 text-center text-muted-foreground">
                              {t?.noChecksYet ?? 'لم تتم إضافة شيكات بعد.'}
                            </TableCell>
                          </TableRow>
                        ) : (
                          checks.map((check) => (
                            <TableRow key={check.id}>
                              <TableCell>{check.checkNumber}</TableCell>
                              <TableCell>{check.bankName || '-'}</TableCell>
                              <TableCell>{check.checkDate}</TableCell>
                              <TableCell>{check.currency}</TableCell>
                              <TableCell className="text-right font-mono">{check.amount.toFixed(2)}</TableCell>
                              <TableCell>
                                <Button type="button" variant="ghost" size="icon" onClick={() => handleRemoveCheck(check.id)}>
                                  <Trash2 className="h-4 w-4" />
                                </Button>
                              </TableCell>
                            </TableRow>
                          ))
                        )}
                      </TableBody>
                    </Table>
                  </div>

                  <div className="flex items-center justify-between rounded-md border bg-background p-3 text-sm">
                    <span>{t?.checksTotalLabel ?? 'إجمالي الشيكات'}</span>
                    <span className="font-mono">{checksTotal.toFixed(2)}</span>
                  </div>
                </div>
              ) : null}
            </TabsContent>

            <TabsContent value="accounting" className="space-y-3">
              <div className="rounded-md border bg-muted/10 p-4 text-sm text-muted-foreground">
                {t?.accountingDescription ?? 'يعرض هذا التبويب الحسابات التي سيتعامل معها قيد إصدار الكوبون حسب شجرة الحسابات الحالية.'}
              </div>
              <div className="grid gap-3 md:grid-cols-2">
                {accountingPreview.map((row) => {
                  const code = String(row.account?.code || row.fallbackCode || '').trim();
                  const name = String(row.account?.nameAr || row.account?.nameEn || row.fallbackName || '').trim();
                  const path = buildAccountPath(row.account);

                  return (
                    <div key={row.key} className="space-y-2 rounded-md border bg-muted/20 p-4">
                      <div className="flex items-center justify-between gap-3">
                        <p className="font-medium">{row.label}</p>
                        <Badge variant="outline">{code || '-'}</Badge>
                      </div>
                      <p>{name || '-'}</p>
                      <p className="text-xs text-muted-foreground">{row.helper}</p>
                      <p className="text-xs text-muted-foreground">{path || (t?.accountPathPending ?? 'سيظهر المسار الكامل عند توفر الحساب في الشجرة.')}</p>
                    </div>
                  );
                })}
              </div>
            </TabsContent>
          </Tabs>

          <DialogFooter>
            <Button type="button" variant="outline" onClick={() => { setShowCreateDialog(false); resetCreateForm(); }}>
              {tGlobal?.cancel ?? 'إلغاء'}
            </Button>
            <Button type="button" onClick={onCreate} disabled={isPending}>
              {t?.createButton ?? 'إنشاء'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <Dialog open={Boolean(detailsCoupon)} onOpenChange={(open) => { if (!open) setDetailsCoupon(null); }}>
        <DialogContent className="w-[calc(100vw-1rem)] max-w-4xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>{t?.couponDetailsTitle ?? 'تفاصيل الكوبون'}</DialogTitle>
            <DialogDescription>
              {detailsCoupon?.couponNumber || '-'}
            </DialogDescription>
          </DialogHeader>

          {detailsCoupon ? (() => {
            const relatedChecks = incomingChecksByCouponId.get(detailsCoupon.id) || [];
            const settlementAccount = getAccountDisplay(detailsCoupon.settlementAccountCode, detailsCoupon.settlementAccountName);
            const liabilityAccount = getAccountDisplay(detailsCoupon.liabilityAccountCode, detailsCoupon.liabilityAccountName);
            const customerAccount = getAccountDisplay(detailsCoupon.customerAccountCode, detailsCoupon.customerName || (t?.customerAccountLabel ?? 'حساب الزبون'));
            const couponCurrencyCode = String(detailsCoupon.currencyCode || '-').trim() || '-';
            const couponBaseCurrencyCode = String(detailsCoupon.baseCurrencyCode || couponCurrencyCode || '-').trim() || '-';
            const couponRate = Number(detailsCoupon.exchangeRate || 1);
            const originalAmount = Number(detailsCoupon.originalAmount || 0);
            const remainingAmount = Number(detailsCoupon.remainingAmount || 0);
            const originalAmountBase = Number.isFinite(Number(detailsCoupon.originalAmountBase)) ? Number(detailsCoupon.originalAmountBase) : (originalAmount * couponRate);
            const remainingAmountBase = Number.isFinite(Number(detailsCoupon.remainingAmountBase)) ? Number(detailsCoupon.remainingAmountBase) : (remainingAmount * couponRate);
            const consumedAmount = Math.max(0, originalAmount - remainingAmount);
            const consumedAmountBase = Math.max(0, originalAmountBase - remainingAmountBase);
            const netFxDifferenceBase = Number(detailsCoupon.cumulativeFxDifferenceBase || 0);

            return (
              <div className="space-y-4">
                <div className="grid gap-3 md:grid-cols-2 xl:grid-cols-4">
                  <div className="rounded-md border bg-muted/20 p-3">
                    <p className="text-xs text-muted-foreground">{t?.titleLabel ?? 'العنوان'}</p>
                    <p className="mt-1 font-medium">{detailsCoupon.title}</p>
                  </div>
                  <div className="rounded-md border bg-muted/20 p-3">
                    <p className="text-xs text-muted-foreground">{t?.customerLabel ?? 'الزبون'}</p>
                    <p className="mt-1 font-medium">{detailsCoupon.customerName || customerTypeLabel(detailsCoupon.customerType)}</p>
                    <p className="text-xs text-muted-foreground">{customerTypeLabel(detailsCoupon.customerType)}</p>
                  </div>
                  <div className="rounded-md border bg-muted/20 p-3">
                    <p className="text-xs text-muted-foreground">{t?.paymentMethod ?? 'آلية السداد'}</p>
                    <p className="mt-1 font-medium">{paymentMethodLabel(detailsCoupon.paymentMethod)}</p>
                  </div>
                  <div className="rounded-md border bg-muted/20 p-3">
                    <p className="text-xs text-muted-foreground">{t?.statusLabel ?? 'الحالة'}</p>
                    <div className="mt-1"><Badge variant={statusVariant(detailsCoupon.status)}>{statusLabel(detailsCoupon.status)}</Badge></div>
                  </div>
                </div>

                <div className="grid gap-3 md:grid-cols-2 xl:grid-cols-3">
                  <div className="rounded-md border p-4">
                    <p className="text-sm font-medium">{t?.settlementAccountLabel ?? 'حساب التسوية'}</p>
                    <p className="mt-2 text-sm">{settlementAccount.code} - {settlementAccount.name}</p>
                    <p className="mt-1 text-xs text-muted-foreground">{settlementAccount.path || (t?.accountPathPending ?? 'لا يوجد مسار محفوظ.')}</p>
                  </div>
                  <div className="rounded-md border p-4">
                    <p className="text-sm font-medium">{t?.couponLiabilityLabel ?? 'حساب التزام الكوبونات'}</p>
                    <p className="mt-2 text-sm">{liabilityAccount.code} - {liabilityAccount.name}</p>
                    <p className="mt-1 text-xs text-muted-foreground">{liabilityAccount.path || (t?.accountPathPending ?? 'لا يوجد مسار محفوظ.')}</p>
                  </div>
                  <div className="rounded-md border p-4">
                    <p className="text-sm font-medium">{t?.customerAccountLabel ?? 'حساب الزبون'}</p>
                    <p className="mt-2 text-sm">{customerAccount.code} - {customerAccount.name}</p>
                    <p className="mt-1 text-xs text-muted-foreground">{customerAccount.path || (t?.accountPathPending ?? 'لا يوجد مسار محفوظ.')}</p>
                  </div>
                </div>

                <div className="rounded-md border p-4">
                  <div className="mb-3">
                    <p className="text-sm font-medium">{t?.currencySnapshotTitle ?? 'ملخص العملة التاريخي'}</p>
                    <p className="text-xs text-muted-foreground">{t?.currencySnapshotHint ?? 'القيم المحاسبية المثبتة وقت إصدار الكوبون.'}</p>
                  </div>
                  <div className="grid gap-3 md:grid-cols-2 xl:grid-cols-4">
                    <div className="rounded-md border bg-muted/20 p-3">
                      <p className="text-xs text-muted-foreground">{t?.couponCurrencyLabel ?? 'عملة الكوبون'}</p>
                      <p className="mt-1 font-medium">{couponCurrencyCode}</p>
                    </div>
                    <div className="rounded-md border bg-muted/20 p-3">
                      <p className="text-xs text-muted-foreground">{t?.baseCurrencyLabel ?? 'عملة الأساس'}</p>
                      <p className="mt-1 font-medium">{couponBaseCurrencyCode}</p>
                    </div>
                    <div className="rounded-md border bg-muted/20 p-3">
                      <p className="text-xs text-muted-foreground">{t?.exchangeRateLabel ?? 'سعر الصرف'}</p>
                      <p className="mt-1 font-medium">{couponRate.toFixed(6)}</p>
                    </div>
                    <div className="rounded-md border bg-muted/20 p-3">
                      <p className="text-xs text-muted-foreground">{t?.rateDateLabel ?? 'تاريخ التثبيت'}</p>
                      <p className="mt-1 font-medium">{detailsCoupon.rateDate ? formatDateStable(detailsCoupon.rateDate) : '-'}</p>
                    </div>
                    <div className="rounded-md border bg-muted/20 p-3">
                      <p className="text-xs text-muted-foreground">{t?.originalAmountLabel ?? 'القيمة الأصلية'}</p>
                      <p className="mt-1 font-mono">{formatAmountWithCurrency(originalAmount, couponCurrencyCode)}</p>
                    </div>
                    <div className="rounded-md border bg-muted/20 p-3">
                      <p className="text-xs text-muted-foreground">{t?.remainingAmountLabel ?? 'الرصيد المتبقي'}</p>
                      <p className="mt-1 font-mono">{formatAmountWithCurrency(remainingAmount, couponCurrencyCode)}</p>
                    </div>
                    <div className="rounded-md border bg-muted/20 p-3">
                      <p className="text-xs text-muted-foreground">{t?.originalAmountBaseLabel ?? 'القيمة الأصلية بالأساس'}</p>
                      <p className="mt-1 font-mono">{formatAmountWithCurrency(originalAmountBase, couponBaseCurrencyCode)}</p>
                    </div>
                    <div className="rounded-md border bg-muted/20 p-3">
                      <p className="text-xs text-muted-foreground">{t?.remainingAmountBaseLabel ?? 'الرصيد المتبقي بالأساس'}</p>
                      <p className="mt-1 font-mono">{formatAmountWithCurrency(remainingAmountBase, couponBaseCurrencyCode)}</p>
                    </div>
                    <div className="rounded-md border bg-muted/20 p-3 md:col-span-2 xl:col-span-4">
                      <p className="text-xs text-muted-foreground">{t?.consumedSummaryLabel ?? 'المستهلك حتى الآن'}</p>
                      <p className="mt-1 font-mono">
                        {formatAmountWithCurrency(consumedAmount, couponCurrencyCode)} / {formatAmountWithCurrency(consumedAmountBase, couponBaseCurrencyCode)}
                      </p>
                    </div>
                    <div className="rounded-md border bg-muted/20 p-3 md:col-span-2 xl:col-span-4">
                      <p className="text-xs text-muted-foreground">{t?.netFxDifferenceLabel ?? 'صافي فروقات العملة المتحقق'}</p>
                      <p className={`mt-1 font-mono ${netFxDifferenceBase > 0 ? 'text-destructive' : netFxDifferenceBase < 0 ? 'text-emerald-600' : ''}`}>
                        {formatAmountWithCurrency(netFxDifferenceBase, couponBaseCurrencyCode)}
                      </p>
                      <p className="text-xs text-muted-foreground">
                        {detailsCoupon.lastFxSettlementAt
                          ? `${t?.lastFxSettlementLabel ?? 'آخر تسوية'}: ${formatDateStable(detailsCoupon.lastFxSettlementAt)}`
                          : (t?.noFxSettlementYet ?? 'لا توجد تسوية فروقات عملة بعد.')}
                      </p>
                    </div>
                  </div>
                </div>

                <div className="rounded-md border p-4">
                  <div className="mb-3 flex items-center justify-between gap-3">
                    <div>
                      <p className="text-sm font-medium">{t?.linkedChecksTitle ?? 'الشيكات المرتبطة'}</p>
                      <p className="text-xs text-muted-foreground">{t?.linkedChecksDescription ?? 'الشيكات التي سُجلت عند إنشاء هذا الكوبون.'}</p>
                    </div>
                    <Badge variant="outline">{relatedChecks.length} {t?.checksCountLabel ?? 'شيك'}</Badge>
                  </div>
                  <div className="rounded-md border bg-background overflow-x-auto">
                    <Table>
                      <TableHeader>
                        <TableRow>
                          <TableHead>{t?.checkNumber ?? 'رقم الشيك'}</TableHead>
                          <TableHead>{t?.bank ?? 'البنك'}</TableHead>
                          <TableHead>{t?.checkDate ?? 'تاريخ الشيك'}</TableHead>
                          <TableHead>{t?.currencyLabel ?? 'العملة'}</TableHead>
                          <TableHead className="text-right">{t?.amountLabel ?? 'القيمة'}</TableHead>
                          <TableHead>{t?.statusLabel ?? 'الحالة'}</TableHead>
                        </TableRow>
                      </TableHeader>
                      <TableBody>
                        {relatedChecks.length === 0 ? (
                          <TableRow>
                            <TableCell colSpan={6} className="h-20 text-center text-muted-foreground">
                              {t?.noLinkedChecks ?? 'لا توجد شيكات مرتبطة بهذا الكوبون.'}
                            </TableCell>
                          </TableRow>
                        ) : (
                          relatedChecks.map((check) => (
                            <TableRow key={check.id}>
                              <TableCell>{check.checkNumber}</TableCell>
                              <TableCell>{check.bankName || '-'}</TableCell>
                              <TableCell>{check.checkDate ? formatDateStable(check.checkDate) : '-'}</TableCell>
                              <TableCell>{check.currency}</TableCell>
                              <TableCell className="text-right font-mono">{Number(check.amount || 0).toFixed(2)}</TableCell>
                              <TableCell>{check.status}</TableCell>
                            </TableRow>
                          ))
                        )}
                      </TableBody>
                    </Table>
                  </div>
                </div>

                {detailsCoupon.notes ? (
                  <div className="rounded-md border p-4">
                    <p className="text-sm font-medium">{t?.notesLabel ?? 'ملاحظات'}</p>
                    <p className="mt-2 whitespace-pre-wrap text-sm text-muted-foreground">{detailsCoupon.notes}</p>
                  </div>
                ) : null}
              </div>
            );
          })() : null}

          <DialogFooter>
            <Button type="button" variant="secondary" onClick={() => handlePrintCouponDetails(detailsCoupon)}>
              {t?.printDetailsButton ?? 'طباعة'}
            </Button>
            <Button type="button" variant="outline" onClick={() => setDetailsCoupon(null)}>
              {tGlobal?.close ?? tGlobal?.cancel ?? 'إغلاق'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </Card>
  );
}
