/**
 * Sales Invoice View Page
 * Display detailed view of a sales invoice
 * URL: /admin/sales/view/[id]
 */

import { Metadata } from 'next';
import Link from 'next/link';
import { redirect } from 'next/navigation';
import { getSession } from '@/lib/auth';
import { handleGetSalesInvoice } from '@/lib/actions/sales-invoice.actions';

import { getCurrencySymbolAsync } from '@/lib/server-currency';
import { formatCurrency } from '@/lib/currency-formatter';
import { formatDateDDMMYYYY, formatDateTimeDDMMYYYY } from '@/lib/utils';
import { formatDateStable, formatDateTimeStable } from '@/lib/formatters';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import SalesInvoiceViewActions from '@/components/admin/sales/sales-invoice-view-actions';
import SalesLogUndoButton from '@/components/admin/sales/sales-log-undo-button';

// Use formatDateDDMMYYYY and formatDateTimeDDMMYYYY from @/lib/utils for consistent date formatting

export const metadata: Metadata = {
  title: 'Sales Invoice Detail | Sales Management',
  description: 'View sales invoice details',
};

interface SalesViewPageProps {
  params: Promise<{
    id: string;
  }>;
}

export default async function SalesViewPage({ params }: SalesViewPageProps) {
  const session = await getSession();
  if (!session?.user) {
    redirect('/login');
  }

  const { id } = await params;
  const result = await handleGetSalesInvoice(id);

  const resolveJournalIds = (invoiceId: string, documentType?: string) => {
    const normalizedType = String(documentType || '').trim();
    if (normalizedType === 'shipment') {
      return {
        primaryId: `JED-SALES-SHIPMENT-${invoiceId}`,
        secondaryId: `JE-SALES-SHIPMENT-${invoiceId}`,
      };
    }
    return {
      primaryId: `JE-SALES-INVOICE-${invoiceId}`,
      secondaryId: '',
    };
  };

  // Load journal entry for this invoice
  let journalEntry: any = null;
  let journalEntryId = '';

  if (!result.success || !result.data) {
    return (
      <Card>
        <CardHeader>
          <CardTitle>الفاتورة غير موجودة</CardTitle>
        </CardHeader>
        <CardContent>
          <p className="text-muted-foreground">تعذر العثور على الفاتورة المطلوبة.</p>
          <Button asChild className="mt-4" variant="outline">
            <Link href="/admin/sales/history">العودة إلى السجل</Link>
          </Button>
        </CardContent>
      </Card>
    );
  }

  const invoice = result.data;
  const journalIds = resolveJournalIds(invoice.id, (invoice as any).documentType);

  try {
    const { pgGetJournalEntryById } = await import('@/lib/postgres/data-access');
    // Try all candidate IDs: posted format first, then draft format
    const candidateIds = [journalIds.secondaryId, journalIds.primaryId].filter(Boolean);
    for (const candidateId of candidateIds) {
      const entry = await pgGetJournalEntryById(candidateId);
      if (entry) {
        journalEntry = entry;
        journalEntryId = String(candidateId);
        break;
      }
    }
    if (!journalEntryId) journalEntryId = journalIds.primaryId;
  } catch {
    journalEntry = null;
    journalEntryId = journalIds.primaryId;
  }

  const isShipmentDoc = String((invoice as any).documentType || '') === 'shipment';
  const isFromPosPartialPayment = Boolean(
    String((invoice as any).restaurantTableId || '').trim() ||
    String((invoice as any).posSessionId || '').trim() ||
    String((invoice as any).source || '').trim() === 'pos'
  );
  const shouldShowAccountingCard = journalEntry !== null || isShipmentDoc
    ? (invoice.postingStatus === 'saved' || invoice.postingStatus === 'posted')
    : invoice.postingStatus === 'posted';
  const activityLog = Array.isArray((invoice as any).activityLog)
    ? ([...(invoice as any).activityLog] as Array<any>).sort(
      (a, b) => new Date(String(b?.timestamp || 0)).getTime() - new Date(String(a?.timestamp || 0)).getTime()
    )
    : [];
  const canUndoInvoiceUpdate = invoice.status === 'active'
    && invoice.postingStatus !== 'posted'
    && invoice.shippingStatus !== 'shipped'
    && invoice.shippingStatus !== 'delivered';
  const currencySymbol = await getCurrencySymbolAsync();
  const fmt = (amount: number) => formatCurrency(amount, currencySymbol);
  const invoiceCurrencyCode = String((invoice as any).currencyCode || '').trim();
  const baseCurrencyCode = String((invoice as any).baseCurrencyCode || '').trim();
  const exchangeRate = Number((invoice as any).exchangeRate || 1) || 1;
  const hasSecondaryCoverage = Boolean(String((invoice as any).secondaryCustomerId || '').trim())
    && Number((invoice as any).secondaryCoveragePercent || 0) > 0;
  const totalInvoiceAmount = Number(invoice.grandTotal || 0);
  const secondaryCoveragePercent = Math.max(0, Math.min(100, Number((invoice as any).secondaryCoveragePercent || 0)));
  const primaryCoveragePercent = Math.max(0, Number((100 - secondaryCoveragePercent).toFixed(2)));
  const secondaryCoverageAmount = hasSecondaryCoverage
    ? Number((invoice as any).secondaryCoverageAmount || ((totalInvoiceAmount * secondaryCoveragePercent) / 100))
    : 0;
  const primaryCoverageAmount = hasSecondaryCoverage
    ? Number((invoice as any).primaryCoverageAmount || (totalInvoiceAmount - secondaryCoverageAmount))
    : totalInvoiceAmount;
  const salesJournalId = journalEntryId || journalIds.primaryId;
  const accountingEntriesLink = `/admin/accounting/entries?je=${encodeURIComponent(salesJournalId)}&q=${encodeURIComponent(invoice.invoiceNumber)}`;

  // Check if invoice is locked (cannot be edited)
  const isEditLockedByStatus = invoice.postingStatus === 'posted'
    || invoice.shippingStatus === 'shipped'
    || invoice.shippingStatus === 'delivered';

  return (
    <div className="space-y-4">
      {isFromPosPartialPayment && (
        <div className="relative rounded-lg border-2 border-emerald-300 bg-gradient-to-r from-emerald-50 via-emerald-50/50 to-emerald-50 p-4 shadow-sm">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-3">
              <div className="flex h-10 w-10 items-center justify-center rounded-full bg-emerald-200">
                <span className="text-lg font-bold text-emerald-700">💵</span>
              </div>
              <div>
                <p className="font-semibold text-emerald-900">فاتورة دفع جزئي من نقطة البيع</p>
                <p className="text-sm text-emerald-700">تم إنشاء هذه الفاتورة من خلال معالجة دفع جزئي في نظام نقطة البيع (POS)</p>
              </div>
            </div>
            <div className="hidden md:block">
              <div className="rounded-full bg-emerald-200 px-4 py-2 text-xs font-semibold text-emerald-800">⚡ دفع جزئي</div>
            </div>
          </div>
        </div>
      )}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold">فاتورة مبيعات</h1>
          <p className="text-muted-foreground mt-1">{invoice.invoiceNumber}</p>
        </div>
        <div className="flex gap-2">
          <Button asChild variant="outline">
            <Link href="/admin/sales/history">رجوع</Link>
          </Button>
          {!isEditLockedByStatus && (
            <Button asChild>
              <Link href={`/admin/sales/edit/${invoice.id}`}>تعديل</Link>
            </Button>
          )}
        </div>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>بيانات عامة</CardTitle>
        </CardHeader>
        <CardContent className="grid grid-cols-1 md:grid-cols-2 gap-4 text-sm">
          <div>
            <p className="text-muted-foreground">الزبون</p>
            <p className="font-medium">{invoice.customerName}</p>
          </div>
          <div>
            <p className="text-muted-foreground">التاريخ</p>
            <p className="font-medium">{formatDateStable(invoice.date)}</p>
          </div>
          <div>
            <p className="text-muted-foreground">الحالة</p>
            <p className="font-medium">{invoice.status === 'cancelled' ? 'ملغاة' : 'فعّالة'}</p>
          </div>
          <div>
            <p className="text-muted-foreground">حالة الترحيل</p>
            <div className="flex items-center gap-2">
              <Badge variant={invoice.postingStatus === 'posted' ? 'default' : 'secondary'}>
                {invoice.postingStatus === 'posted' ? 'مرحّل' : invoice.postingStatus === 'saved' ? 'محفوظ' : invoice.postingStatus === 'draft' ? 'مسودة' : (invoice.postingStatus || 'محفوظ')}
              </Badge>
              {shouldShowAccountingCard && (
                <Link href={accountingEntriesLink} className="text-xs text-primary underline">
                  عرض القيود
                </Link>
              )}
            </div>
          </div>
          <div>
            <p className="text-muted-foreground">حالة الدفع</p>
            <p className="font-medium">
              {invoice.paymentStatus === 'paid' ? (
                <span className="text-emerald-700 font-semibold">✓ مدفوعة</span>
              ) : invoice.paymentStatus === 'partial' ? (
                <span className="text-amber-700 font-semibold">💵 مدفوعة جزئياً</span>
              ) : invoice.paymentStatus === 'overdue' ? (
                <span className="text-rose-700 font-semibold">⚠ متأخرة</span>
              ) : (
                <span className="text-slate-700">غير مدفوعة</span>
              )}
            </p>
          </div>
          {invoice.shippingStatus && (
            <div>
              <p className="text-muted-foreground">حالة الشحن</p>
              <p className="font-medium">
                {invoice.shippingStatus === 'shipped' ? 'مشحون' : invoice.shippingStatus === 'delivered' ? 'مسلّم' : invoice.shippingStatus === 'partial' ? 'جزئي' : invoice.shippingStatus === 'cancelled' ? 'ملغى' : 'معلّق'}
              </p>
            </div>
          )}
          {invoice.salesRepName && (
            <div>
              <p className="text-muted-foreground">مندوب المبيعات</p>
              <p className="font-medium">{invoice.salesRepName}</p>
            </div>
          )}
          {(invoice as any).documentType && (
            <div>
              <p className="text-muted-foreground">نوع المستند</p>
              <p className="font-medium">
                {(invoice as any).documentType === 'shipment' ? 'ارسالية (لوجستي)' : 'فاتورة ضريبية'}
              </p>
            </div>
          )}
          {(invoice as any).source === 'store' && (
            <div>
              <p className="text-muted-foreground">المصدر</p>
              <p className="font-medium">طلب متجر</p>
            </div>
          )}
          <div>
            <p className="text-muted-foreground">عملة الفاتورة</p>
            <p className="font-medium">{invoiceCurrencyCode || currencySymbol || '₪'}</p>
          </div>
          <div>
            <p className="text-muted-foreground">عملة الأساس</p>
            <p className="font-medium">{baseCurrencyCode || currencySymbol || '₪'}</p>
          </div>
          <div>
            <p className="text-muted-foreground">سعر الصرف</p>
            <p className="font-medium" lang="en" dir="ltr">{exchangeRate.toFixed(4)}</p>
          </div>
        </CardContent>
      </Card>

      {hasSecondaryCoverage && (
        <Card>
          <CardHeader>
            <CardTitle>توزيع التغطية بين العملاء</CardTitle>
          </CardHeader>
          <CardContent className="grid grid-cols-1 gap-4 text-sm md:grid-cols-2">
            <div className="rounded-md border p-3">
              <p className="text-muted-foreground">العميل الرئيسي</p>
              <p className="font-medium">{invoice.customerName}</p>
              <p className="mt-1 text-xs text-muted-foreground">النسبة: {primaryCoveragePercent.toFixed(2)}%</p>
              <p className="font-semibold" lang="en" dir="ltr">
                {primaryCoverageAmount.toFixed(2)} {invoiceCurrencyCode || ''}
              </p>
              <p className="text-xs text-muted-foreground" lang="en" dir="ltr">
                ≈ {(primaryCoverageAmount * exchangeRate).toFixed(2)} {baseCurrencyCode || ''}
              </p>
            </div>
            <div className="rounded-md border p-3">
              <p className="text-muted-foreground">العميل الثانوي</p>
              <p className="font-medium">{String((invoice as any).secondaryCustomerName || (invoice as any).secondaryCustomerId || '-')}</p>
              <p className="mt-1 text-xs text-muted-foreground">النسبة: {secondaryCoveragePercent.toFixed(2)}%</p>
              <p className="font-semibold" lang="en" dir="ltr">
                {secondaryCoverageAmount.toFixed(2)} {invoiceCurrencyCode || ''}
              </p>
              <p className="text-xs text-muted-foreground" lang="en" dir="ltr">
                ≈ {(secondaryCoverageAmount * exchangeRate).toFixed(2)} {baseCurrencyCode || ''}
              </p>
            </div>
          </CardContent>
        </Card>
      )}

      {((invoice as any).realEstateProjectId || (invoice as any).realEstateUnitId) && (
        <Card>
          <CardHeader>
            <CardTitle>بيانات العقد العقاري</CardTitle>
          </CardHeader>
          <CardContent className="grid grid-cols-1 gap-4 text-sm md:grid-cols-2 lg:grid-cols-4">
            <div>
              <p className="text-muted-foreground">المشروع</p>
              <p className="font-medium">{String((invoice as any).realEstateProjectName || (invoice as any).realEstateProjectId || '-')}</p>
            </div>
            <div>
              <p className="text-muted-foreground">الوحدة</p>
              <p className="font-medium">{String((invoice as any).realEstateUnitName || (invoice as any).realEstateUnitId || '-')}</p>
            </div>
            <div>
              <p className="text-muted-foreground">رقم العقد</p>
              <p className="font-medium">{String((invoice as any).realEstateContractNumber || '-')}</p>
            </div>
            <div>
              <p className="text-muted-foreground">تاريخ العقد</p>
              <p className="font-medium">{formatDateStable((invoice as any).realEstateContractDate)}</p>
            </div>
            <div>
              <p className="text-muted-foreground">تاريخ التسليم</p>
              <p className="font-medium">{formatDateStable((invoice as any).realEstateHandoverDate)}</p>
            </div>
            <div>
              <p className="text-muted-foreground">قيمة العقد</p>
              <p className="font-semibold">{fmt(Number((invoice as any).realEstateContractValue || 0))}</p>
            </div>
            <div>
              <p className="text-muted-foreground">الدفعة الحالية</p>
              <p className="font-semibold text-emerald-700">{fmt(Number((invoice as any).realEstateDownPayment || invoice.amountReceived || 0))}</p>
            </div>
            <div>
              <p className="text-muted-foreground">الرصيد المؤجل</p>
              <p className="font-semibold text-amber-700">{fmt(Number((invoice as any).realEstateDeferredAmount || invoice.amountDue || 0))}</p>
            </div>
          </CardContent>
        </Card>
      )}

      {/* Linked documents section */}
      {((invoice as any).taxInvoiceId || (Array.isArray((invoice as any).linkedShipmentIds) && (invoice as any).linkedShipmentIds.length > 0)) && (
        <Card>
          <CardHeader>
            <CardTitle>المستندات المرتبطة</CardTitle>
          </CardHeader>
          <CardContent className="space-y-2 text-sm">
            {(invoice as any).taxInvoiceId && (
              <div className="flex items-center justify-between rounded border p-3">
                <span className="text-muted-foreground">الفاتورة الضريبية</span>
                <Link href={`/admin/sales/view/${(invoice as any).taxInvoiceId}`} className="font-medium text-primary underline hover:no-underline">
                  عرض الفاتورة الضريبية ←
                </Link>
              </div>
            )}
            {Array.isArray((invoice as any).linkedShipmentIds) && (invoice as any).linkedShipmentIds.map((shipId: string) => (
              <div key={shipId} className="flex items-center justify-between rounded border p-3">
                <span className="text-muted-foreground">إرسالية مرتبطة</span>
                <Link href={`/admin/sales/view/${shipId}`} className="font-medium text-primary underline hover:no-underline">
                  عرض الإرسالية ←
                </Link>
              </div>
            ))}
          </CardContent>
        </Card>
      )}

      <Card>
        <CardHeader>
          <CardTitle>بنود الفاتورة</CardTitle>
        </CardHeader>
        <CardContent>
          {invoice.items.length === 0 ? (
            <p className="text-muted-foreground text-sm">لا توجد أصناف.</p>
          ) : (
            <div className="relative w-full overflow-auto">
              <div className="relative w-full overflow-auto">
                <table className="w-full caption-bottom text-sm">
                  <thead className="[&_tr]:border-b">
                    <tr className="border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted">
                      <th className="h-12 px-4 text-left align-middle font-medium text-muted-foreground">الصنف</th>
                      <th className="h-12 px-4 text-left align-middle font-medium text-muted-foreground">الكمية</th>
                      <th className="h-12 px-4 text-left align-middle font-medium text-muted-foreground">السعر</th>
                      <th className="h-12 px-4 text-left align-middle font-medium text-muted-foreground">المستودع</th>
                      <th className="h-12 px-4 text-left align-middle font-medium text-muted-foreground">الرف</th>
                      <th className="h-12 px-4 text-left align-middle font-medium text-muted-foreground">خصم %</th>
                      <th className="h-12 px-4 text-left align-middle font-medium text-muted-foreground">خصم</th>
                      <th className="h-12 px-4 text-left align-middle font-medium text-muted-foreground">ضريبة %</th>
                      <th className="h-12 px-4 text-left align-middle font-medium text-muted-foreground">قيمة الضريبة</th>
                      <th className="h-12 px-4 text-left align-middle font-medium text-muted-foreground">بونص</th>
                      <th className="h-12 px-4 align-middle font-medium text-muted-foreground text-right">الإجمالي</th>
                    </tr>
                  </thead>
                  <tbody className="[&_tr:last-child]:border-0">
                    {invoice.items.map((item, index) => {
                      const quantity = Number(item.quantity || 0);
                      const unitPrice = Number(item.unitPrice || 0);
                      const gross = quantity * unitPrice;
                      const lineDiscountPercent = Number(item.lineDiscountPercent || 0);
                      const lineDiscountAmount = Number(
                        item.lineDiscountAmount
                        ?? (lineDiscountPercent > 0 ? (gross * lineDiscountPercent) / 100 : 0)
                      );
                      const lineNet = Math.max(0, gross - lineDiscountAmount);
                      const taxRate = Number(item.taxRate || 0);
                      const taxAmount = Number(item.taxAmount ?? (lineNet * taxRate) / 100);
                      const lineTotal = Number(item.total ?? (lineNet + taxAmount));
                      const warehouseName = String((item as any).warehouseName || (item as any).warehouseId || (invoice as any).warehouseName || '-');
                      const shelfName = String((item as any).shelfName || (item as any).shelfId || '-');
                      const bonusQty = Number((item as any).bonusQuantity || (item as any).bonusQty || 0);

                      return (
                        <tr key={`${item.materialId || 'item'}-${index}`} className="border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted">
                          <td className="p-4 align-middle">{item.name || item.materialId || '-'}</td>
                          <td className="p-4 align-middle">{quantity}</td>
                          <td className="p-4 align-middle">{fmt(unitPrice)}</td>
                          <td className="p-4 align-middle">{warehouseName}</td>
                          <td className="p-4 align-middle">{shelfName}</td>
                          <td className="p-4 align-middle">{lineDiscountPercent > 0 ? lineDiscountPercent.toFixed(2) : '-'}</td>
                          <td className="p-4 align-middle">{lineDiscountAmount > 0 ? fmt(lineDiscountAmount) : '-'}</td>
                          <td className="p-4 align-middle">{taxRate > 0 ? taxRate.toFixed(2) : '-'}</td>
                          <td className="p-4 align-middle">{taxAmount > 0 ? fmt(taxAmount) : '-'}</td>
                          <td className="p-4 align-middle">{bonusQty > 0 ? bonusQty : 0}</td>
                          <td className="p-4 align-middle text-right">{fmt(lineTotal)}</td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </div>
            </div>
          )}
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>الملخص المالي</CardTitle>
        </CardHeader>
        <CardContent className="grid grid-cols-1 md:grid-cols-2 gap-4 text-sm">
          <div>
            <p className="text-muted-foreground">الإجمالي قبل الخصم والضريبة</p>
            <p className="font-medium">{fmt(Number(invoice.subTotal || 0))}</p>
          </div>
          {Number((invoice as any).totalDiscount || (invoice as any).invoiceDiscountAmount || 0) > 0 && (
            <div>
              <p className="text-muted-foreground">الخصم</p>
              <p className="font-medium text-amber-600">
                - {fmt(Number((invoice as any).totalDiscount || (invoice as any).invoiceDiscountAmount || 0))}
              </p>
            </div>
          )}
          <div>
            <p className="text-muted-foreground">الضريبة</p>
            <p className="font-medium">{fmt(Number(invoice.taxAmount || 0))}</p>
          </div>
          <div>
            <p className="text-muted-foreground">الإجمالي النهائي</p>
            <p className="font-semibold">{fmt(Number(invoice.grandTotal || 0))}</p>
          </div>
          <div>
            <p className="text-muted-foreground">المبلغ المدفوع</p>
            <p className="font-semibold text-emerald-700">{fmt(Number(invoice.amountReceived || 0))}</p>
          </div>
          <div>
            <p className="text-muted-foreground">المتبقي</p>
            <p className={`font-semibold ${Number(invoice.amountDue || 0) > 0 ? 'text-rose-600' : 'text-emerald-700'}`}>
              {fmt(Number(invoice.amountDue || 0))}
            </p>
          </div>
        </CardContent>
      </Card>

      <SalesInvoiceViewActions
        invoice={invoice}
        userId={session.user.id}
        userName={session.user.name}
      />

      <Card>
        <CardHeader>
          <CardTitle>سجل النشاط</CardTitle>
        </CardHeader>
        <CardContent>
          {activityLog.length === 0 ? (
            <p className="text-sm text-muted-foreground">لا توجد أحداث مسجلة لهذه الفاتورة بعد.</p>
          ) : (
            <div className="space-y-2">
              {activityLog.map((entry: any, index: number) => (
                <div key={String(entry?.id || index)} className="rounded border p-3 text-sm">
                  <div className="flex flex-wrap items-center justify-between gap-2">
                    <p className="font-medium">{String(entry?.message || 'بدون وصف')}</p>
                    <Badge variant="outline" className="text-xs">{String(entry?.action || 'event')}</Badge>
                  </div>
                  <p className="text-xs text-muted-foreground mt-1">
                    بواسطة: {String(entry?.byName || entry?.by || '-')} | {formatDateTimeStable(String(entry?.timestamp || ''))}
                  </p>
                  {Array.isArray(entry?.details?.changedFields) && entry.details.changedFields.length > 0 && (
                    <div className="mt-2 space-y-1 rounded bg-muted/40 p-2">
                      <p className="text-xs font-medium">التغييرات:</p>
                      {entry.details.changedFields.map((change: any, changeIndex: number) => (
                        <p key={`${String(change?.key || 'field')}-${changeIndex}`} className="text-xs text-muted-foreground">
                          <span className="font-medium text-foreground">{String(change?.label || change?.key || 'حقل')}</span>
                          :
                          {' '}<span className="line-through">{String(change?.before ?? '-')}</span>
                          {' '}→{' '}
                          <span className="font-medium text-foreground">{String(change?.after ?? '-')}</span>
                        </p>
                      ))}
                    </div>
                  )}
                  {canUndoInvoiceUpdate && index === 0 && String(entry?.action || '') === 'updated' && entry?.details?.undoPatch && (
                    <div className="mt-2 flex justify-end">
                      <SalesLogUndoButton
                        invoiceId={invoice.id}
                        userId={session.user.id}
                        userName={session.user.name}
                      />
                    </div>
                  )}
                </div>
              ))}
            </div>
          )}
        </CardContent>
      </Card>

        {(shouldShowAccountingCard || journalEntry) && (
          <Card>
            <CardHeader>
              <CardTitle>القيد المحاسبي</CardTitle>
            </CardHeader>
            <CardContent>
              {!journalEntry ? (
                <p className="text-sm text-amber-600">لم يتم إنشاء القيد المحاسبي بعد لهذه الفاتورة. سيتم إنشاؤه عند ترحيل الفاتورة.</p>
              ) : (
                <div className="space-y-3">
                  <div className="flex flex-wrap gap-4 text-xs text-muted-foreground mb-2">
                    <span>رقم القيد: <span className="font-mono font-bold text-foreground">{journalEntry.id}</span></span>
                    <span>الحالة: <span className="font-medium text-foreground">{String(journalEntry.status || 'posted') === 'draft' ? 'مسودة' : 'أصلي'}</span></span>
                    <span>التاريخ: <span className="font-medium text-foreground">{formatDateStable(journalEntry.date)}</span></span>
                  </div>
                  <div className="overflow-x-auto">
                    <table className="w-full text-sm border-collapse">
                      <thead>
                        <tr className="border-b bg-muted/50">
                          <th className="text-right p-2 font-medium">الحساب</th>
                          <th className="text-right p-2 font-medium">البيان</th>
                          <th className="text-right p-2 font-medium">مدين</th>
                          <th className="text-right p-2 font-medium">دائن</th>
                        </tr>
                      </thead>
                      <tbody>
                        {(journalEntry.lines || []).map((line: any, idx: number) => (
                          <tr key={idx} className="border-b hover:bg-muted/30">
                            <td className="p-2 font-mono text-xs">{line.accountCode} - {line.accountName}</td>
                            <td className="p-2 text-muted-foreground text-xs">{line.description}</td>
                            <td className="p-2 font-semibold text-emerald-700">{Number(line.debit || 0) > 0 ? fmt(Number(line.debit)) : '-'}</td>
                            <td className="p-2 font-semibold text-rose-700">{Number(line.credit || 0) > 0 ? fmt(Number(line.credit)) : '-'}</td>
                          </tr>
                        ))}
                      </tbody>
                      <tfoot>
                        <tr className="border-t-2 bg-muted/30 font-bold">
                          <td className="p-2" colSpan={2}>الإجمالي</td>
                          <td className="p-2 text-emerald-700">{fmt((journalEntry.lines || []).reduce((s: number, l: any) => s + Number(l.debit || 0), 0))}</td>
                          <td className="p-2 text-rose-700">{fmt((journalEntry.lines || []).reduce((s: number, l: any) => s + Number(l.credit || 0), 0))}</td>
                        </tr>
                      </tfoot>
                    </table>
                  </div>
                </div>
              )}
            </CardContent>
          </Card>
        )}
    </div>
  );
}
