import Link from "next/link";
import { notFound } from "next/navigation";
import { format } from "date-fns";
import { verifySession } from "@/lib/auth";

import { getCurrentLocale, getTranslations } from "@/lib/i18n";
import { getCurrencySymbolAsync } from "@/lib/server-currency";
import { formatCurrency as formatCurrencyUtil } from "@/lib/currency-formatter";
import { formatDateDDMMYYYY, formatDateTimeDDMMYYYY } from "@/lib/utils";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Badge } from "@/components/ui/badge";
import PurchaseHistoryActions from "@/components/admin/purchase-history-actions";
import { AlertCircle, CheckCircle2 } from "lucide-react";
import { handleCreateManualPurchaseInventoryEffect, handleCreateWorkTaskFromPurchaseOrder } from "@/lib/actions";
import type { PurchaseOrder } from "@/lib/types";

export default async function PurchaseOrderViewPage({
  params,
  searchParams,
}: {
  params: Promise<{ id: string }>;
  searchParams?: Promise<{ workTaskError?: string; lockedBy?: string; workTaskCreated?: string; manualInventoryCreated?: string; manualInventoryError?: string }>;
}) {
  const { id } = await params;
  const resolvedSearchParams = searchParams ? await searchParams : undefined;
  const workTaskError = String(resolvedSearchParams?.workTaskError || '').trim();
  const workTaskCreated = String(resolvedSearchParams?.workTaskCreated || '').trim() === '1';
  const manualInventoryCreated = String(resolvedSearchParams?.manualInventoryCreated || '').trim() === '1';
  const manualInventoryError = String(resolvedSearchParams?.manualInventoryError || '').trim();
  const lockedBy = String(resolvedSearchParams?.lockedBy || '').trim();
  const session = await verifySession();
  if (!session?.user || session.user.role !== "admin") return notFound();

  const locale = await getCurrentLocale();
  const t = getTranslations(locale);
  const tPurchases = t.Purchases ?? {};
  const tGlobal = t.Global ?? {};

  let order = undefined;
  let suppliers = [];
  let materials = [];
  let warehouses = [];
  let transferDocs = [];
  let linkedPayments = [];
  let returns = [];
  let inventoryMovements = [];
  let journalEntries = [];
  let shipments = [];
  let currencies = [];
  let checksReceived: any[] = [];

  
  const {
  pgGetPurchaseOrders,
  pgGetCurrencies,
  pgGetSuppliers,
  pgGetMaterials,
  pgGetWarehouses,
  pgGetInternalTransfers,
  pgGetSupplierPayments,
  pgGetPurchaseReturns,
  pgGetInventoryMovements,
  pgGetJournalEntries,
  pgGetShipments,
  pgGetChecksReceived,
  } = await import('@/lib/postgres/data-access');

  const [
  ordersResult,
  currenciesResult,
  suppliersResult,
  materialsResult,
  warehousesResult,
  transferDocsResult,
  supplierPaymentsResult,
  returnsResult,
  inventoryMovementsResult,
  journalEntriesResult,
  shipmentsResult,
  checksReceivedResult,
  ] = await Promise.all([
  pgGetPurchaseOrders({ page: 1, pageSize: 5000 }),
  pgGetCurrencies({ page: 1, pageSize: 500 }),
  pgGetSuppliers({ page: 1, pageSize: 5000 }),
  pgGetMaterials({ page: 1, pageSize: 5000 }),
  pgGetWarehouses({ page: 1, pageSize: 5000 }),
  pgGetInternalTransfers({ page: 1, pageSize: 5000 }),
  pgGetSupplierPayments({ page: 1, pageSize: 5000 }),
  pgGetPurchaseReturns({ page: 1, pageSize: 5000 }),
  pgGetInventoryMovements({ page: 1, pageSize: 10000 }),
  pgGetJournalEntries({ page: 1, pageSize: 5000 }),
  pgGetShipments({ page: 1, pageSize: 5000 }),
  pgGetChecksReceived({ page: 1, pageSize: 5000 }),
  ]);

  const orders = (ordersResult.items || []) as PurchaseOrder[];
  order = orders.find((candidate) => candidate.id === id) || order;
  currencies = (currenciesResult.items || []) as typeof currencies;
  suppliers = (suppliersResult.items || []) as typeof suppliers;
  materials = (materialsResult.items || []) as typeof materials;
  warehouses = (warehousesResult.items || []) as typeof warehouses;
  checksReceived = (checksReceivedResult.items || []) as any[];

  if (order) {
  transferDocs = ((transferDocsResult.items || []) as typeof transferDocs).filter(
    (doc) => doc.sourcePurchaseOrderId === order!.id
  );
  linkedPayments = ((supplierPaymentsResult.items || []) as typeof linkedPayments).filter(
    (payment) =>
      payment.status !== 'cancelled' &&
      (payment.allocations || []).some(
        (allocation) => allocation.purchaseOrderId === order!.id && Number(allocation.amount || 0) > 0
      )
  );
  returns = ((returnsResult.items || []) as typeof returns).filter((ret) => ret.purchaseOrderId === order!.id);
  inventoryMovements = ((inventoryMovementsResult.items || []) as typeof inventoryMovements).filter(
    (movement) => movement.invoiceId === order!.id
  );
  journalEntries = ((journalEntriesResult.items || []) as typeof journalEntries).filter(
    (entry) => entry.referenceId === order!.id
  );
  shipments = ((shipmentsResult.items || []) as typeof shipments).filter((shipment) => shipment.invoiceId === order!.id);
  }
  

  if (!order) return notFound();

  const defaultCurrencySymbol = await getCurrencySymbolAsync();
  const currencySymbolByCode = new Map(
    (Array.isArray(currencies) ? currencies : []).map((currency: any) => [String(currency?.code || '').trim(), String(currency?.symbol || '').trim()])
  );
  const getSymbol = (currencyCode?: string) => {
    const code = String(currencyCode || '').trim();
    return (code && currencySymbolByCode.get(code)) || defaultCurrencySymbol;
  };
  const formatAmount = (amount: number, currencyCode?: string) => formatCurrencyUtil(amount, getSymbol(currencyCode));

  const supplier = suppliers.find((s) => s.id === order.supplierId);
  const warehouseById = new Map(warehouses.map((warehouse) => [warehouse.id, warehouse]));
  const resolveWarehouseName = (warehouseId?: string) => {
    const idVal = String(warehouseId || '').trim();
    if (!idVal) return '-';
    return warehouseById.get(idVal)?.name || idVal;
  };
  const resolveShelfName = (warehouseId?: string, shelfId?: string) => {
    const warehouse = warehouseById.get(String(warehouseId || '').trim());
    const idVal = String(shelfId || '').trim();
    if (!idVal) return '-';
    return warehouse?.shelves?.find((shelf) => shelf.id === idVal)?.name || idVal;
  };

  const isShipmentDoc = String(order.documentType || 'tax_invoice') === 'shipment';
  const isPosted = (order.postingStatus || "posted") === "posted";
  const postingStatus: 'draft' | 'saved' | 'posted' = (order.postingStatus || 'posted') as any;
  const canEdit = order.status === "active" && !isPosted;

  const hasTransferDocs = transferDocs.some((doc) => doc.status === "active");
  const sortTransferDocsDesc = (a: any, b: any) => {
    const aTime = new Date(String(a.date || a.createdAt || '')).getTime();
    const bTime = new Date(String(b.date || b.createdAt || '')).getTime();
    if (Number.isFinite(aTime) && Number.isFinite(bTime) && aTime !== bTime) {
      return bTime - aTime;
    }
    return String(b.transferNumber || '').localeCompare(String(a.transferNumber || ''), 'en', { numeric: true });
  };
  const cancelledTransferDocs = transferDocs.filter((doc) => doc.status === "cancelled");
  const activeTransferDocs = transferDocs.filter((doc) => doc.status === 'active');
  const cancelledSourceTagRegex = /\[source-cancelled:([^\]]+)\]/;
  const recreatedCancelledDocIds = new Set(
    activeTransferDocs
      .map((doc) => {
        const match = String(doc.note || '').match(cancelledSourceTagRegex);
        return match?.[1] ? String(match[1]).trim() : '';
      })
      .filter((idValue) => idValue)
  );
  let pendingCancelledTransferDocs = cancelledTransferDocs.filter(
    (doc) => !recreatedCancelledDocIds.has(String(doc.id || '').trim())
  );
  const hasLegacyReplacementDoc = activeTransferDocs.some((doc) => {
    const note = String(doc.note || '');
    return note.includes('مهمة عمل لفاتورة مشتريات') || note.includes('(إعادة إنشاء)');
  });
  if (hasLegacyReplacementDoc && pendingCancelledTransferDocs.length > 0) {
    const sortedPending = pendingCancelledTransferDocs.slice().sort(sortTransferDocsDesc);
    sortedPending.shift();
    pendingCancelledTransferDocs = sortedPending;
  }
  const latestPendingCancelledTransferDoc = pendingCancelledTransferDocs
    .slice()
    .sort(sortTransferDocsDesc)[0];
  const hasSupplierPayments = linkedPayments.length > 0;
  const hasPurchaseReturns = returns.some((ret) => ret.status !== "cancelled");
  const hasOtherMovements = inventoryMovements.some((movement) => movement.referenceType !== "purchase_order");
  const hasOtherJournals = journalEntries.some((entry) => entry.referenceType !== "purchase_order");

  const canCancel = order.status === "active" && !hasTransferDocs && !hasSupplierPayments && !hasPurchaseReturns && !hasOtherMovements && !hasOtherJournals;
  const canRestore = order.status === "cancelled";
  const canAdvancePosting = order.status === 'active' && (
    postingStatus === 'draft' || (!isShipmentDoc && postingStatus === 'saved')
  );
  const canCreateWorkTaskOnDemand =
    order.status === 'active' &&
    !hasTransferDocs;
  const hasPurchaseInventoryMovements = inventoryMovements.some((movement) => movement.referenceType === 'purchase_order');
  const canCreateManualInventoryEffect =
    order.status === 'active' &&
    (isShipmentDoc ? (postingStatus === 'saved' || postingStatus === 'posted') : postingStatus === 'posted') &&
    !hasPurchaseInventoryMovements;
  const cancelBlockedReason = hasTransferDocs
    ? (tPurchases.cancelBlockedTransferDocs ?? "لا يمكن الإلغاء لوجود إرساليات داخلية مرتبطة بهذه الفاتورة.")
    : hasSupplierPayments
      ? (tPurchases.cancelBlockedSupplierPayments ?? "لا يمكن الإلغاء لوجود سندات دفع مرتبطة بهذه الفاتورة.")
      : hasPurchaseReturns
        ? (tPurchases.cancelBlockedPurchaseReturns ?? "لا يمكن الإلغاء لوجود مردودات مشتريات مرتبطة بهذه الفاتورة.")
        : (hasOtherMovements || hasOtherJournals)
          ? (tPurchases.cancelBlockedOtherMovements ?? "لا يمكن الإلغاء لوجود حركات أخرى مرتبطة بهذه الفاتورة.")
          : order.status !== "active"
            ? (tPurchases.cancelBlockedNotActive ?? "الإلغاء متاح للفواتير النشطة فقط.")
            : undefined;

  const getStatusBadge = (status: string) => {
    switch (status) {
      case "active":
        return <Badge variant="default">{tPurchases.statusActive ?? "نشط"}</Badge>;
      case "received":
        return <Badge variant="secondary">{tPurchases.statusReceived ?? "مستلم"}</Badge>;
      case "cancelled":
        return <Badge variant="destructive">{tPurchases.statusCancelled ?? "ملغى"}</Badge>;
      default:
        return <Badge variant="outline">{status}</Badge>;
    }
  };

  const getPostingStatusBadge = (postingStatus?: string) => {
    const status = postingStatus || "posted";
    switch (status) {
      case "draft":
        return <Badge variant="outline">{tPurchases.postingDraftLabel ?? "مسودة"}</Badge>;
      case "saved":
        return <Badge variant="secondary">{tPurchases.postingSavedLabel ?? "محفوظ"}</Badge>;
      case "posted":
        return <Badge variant="default">{tPurchases.postingPostedLabel ?? "مرحل"}</Badge>;
      default:
        return <Badge variant="outline">{status}</Badge>;
    }
  };

  const materialName = (materialId: string) => materials.find((m) => m.id === materialId)?.name || materialId;

  const events: Array<{
    date: string;
    type: string;
    reference: string;
    status: string;
    details?: string;
    href?: string;
  }> = [
    ...transferDocs.map((doc) => ({
      date: doc.createdAt || doc.date,
      type: tPurchases.transferDocEvent ?? "إرسالية داخلية",
      reference: doc.transferNumber || doc.id,
      status: doc.status || "-",
      details: doc.receiptStatus ? `${tPurchases.receiptStatus ?? "الاستلام"}: ${doc.receiptStatus}` : undefined,
      href: `/admin/data/internal-transfers/${encodeURIComponent(doc.id)}`,
    })),
    ...linkedPayments.map((payment) => ({
      date: payment.date,
      type: tPurchases.supplierPaymentEvent ?? "سند دفع",
      reference: payment.reference || payment.id,
      status: tPurchases.postingSavedLabel ?? "محفوظ",
      details: `${formatAmount(payment.amount, payment.currencyCode)} ${(payment.currencyCode || "").trim()}`.trim(),
      href: `/admin/purchases/payment?paymentId=${encodeURIComponent(payment.id)}`,
    })),
    ...returns.map((ret) => ({
      date: ret.createdAt,
      type: tPurchases.purchaseReturnEvent ?? "مردود مشتريات",
      reference: ret.returnNumber || ret.id,
      status: ret.status,
      details: formatAmount(ret.totalAmount, order.currencyCode),
      href: `/admin/purchases/returns/${ret.id}`,
    })),
    ...shipments.map((shipment) => ({
      date: shipment.date,
      type: tPurchases.shipmentEvent ?? "شحنة",
      reference: shipment.shipmentNumber || shipment.id,
      status: shipment.status,
      details: shipment.shipmentType,
      href: `/admin/data/internal-transfers?shipmentId=${encodeURIComponent(shipment.id)}`,
    })),
    ...inventoryMovements.map((movement) => ({
      date: movement.date,
      type: tPurchases.inventoryMovementEvent ?? "حركة مخزنية",
      reference: movement.referenceId,
      status: movement.referenceType,
      details: `${tPurchases.quantity ?? "الكمية"}: +${movement.quantityIn || 0} / -${movement.quantityOut || 0}`,
      href: `/admin/data/material-movements?invoiceId=${encodeURIComponent(order.id)}`,
    })),
    ...journalEntries.map((entry) => ({
      date: entry.date,
      type: tPurchases.journalEvent ?? "قيد محاسبي",
      reference: entry.id,
      status: entry.referenceType,
      details: entry.description,
      href: `/admin/accounting/entries?referenceId=${encodeURIComponent(order.id)}`,
    })),
  ].sort((a, b) => new Date(b.date || 0).getTime() - new Date(a.date || 0).getTime());

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <h1 className="text-2xl font-semibold">
          {isShipmentDoc
            ? (tPurchases.viewShipmentTitle ?? 'معاينة إرسالية المشتريات')
            : (tPurchases.viewInvoiceTitle ?? "معاينة فاتورة الشراء")}
        </h1>
        <div className="flex items-center gap-4">
          {canEdit ? (
            <Link href={`/admin/purchases/edit/${order.id}`} className="text-sm underline text-primary">
              {tPurchases.openInInvoiceForm ?? 'فتح في نموذج الفاتورة'}
            </Link>
          ) : null}
          <Link href="/admin/purchases/history" className="text-sm underline">
            {tGlobal.back || "رجوع"}
          </Link>
        </div>
      </div>

      {workTaskError === 'locked' && (
        <Alert className="border-red-300 bg-red-50 text-red-900">
          <AlertTitle>تعذر إنشاء مهمة العمل</AlertTitle>
          <AlertDescription>
            المستند قيد المعالجة حالياً بواسطة المستخدم: {lockedBy || 'مستخدم آخر'}.
          </AlertDescription>
        </Alert>
      )}

      {workTaskCreated && (
        <Alert className="border-emerald-300 bg-emerald-50 text-emerald-900">
          <CheckCircle2 className="h-4 w-4" />
          <AlertTitle>تم إنشاء مهمة العمل</AlertTitle>
          <AlertDescription>
            تم إنشاء مهمة عمل بنجاح، وتم إنشاء سند إرسالية داخلية بحالة معلقة ويمكن متابعته من شاشة مهام العمل والإرساليات الداخلية.
          </AlertDescription>
        </Alert>
      )}

      {manualInventoryCreated && (
        <Alert className="border-emerald-300 bg-emerald-50 text-emerald-900">
          <CheckCircle2 className="h-4 w-4" />
          <AlertTitle>تم إنشاء الحركة المخزنية</AlertTitle>
          <AlertDescription>
            تم إنشاء شحنة وحركة مخزنية لهذه الفاتورة بنجاح.
          </AlertDescription>
        </Alert>
      )}

      {manualInventoryError && (
        <Alert className="border-red-300 bg-red-50 text-red-900">
          <AlertCircle className="h-4 w-4" />
          <AlertTitle>تعذر إنشاء الحركة المخزنية</AlertTitle>
          <AlertDescription>
            {manualInventoryError === 'already_exists'
              ? 'تم إنشاء حركة مخزنية مسبقاً لهذه الفاتورة.'
              : manualInventoryError === 'no_inventory_items'
                ? 'لا توجد أصناف مخزنية صالحة لإنشاء الحركة.'
                : manualInventoryError === 'posting_not_ready'
                  ? 'لا يمكن إنشاء الحركة قبل أن تكون حالة المستند جاهزة (الإرسالية: محفوظ/مرحل، الفاتورة: مرحل).'
                : manualInventoryError === 'not_active'
                  ? 'الحركة اليدوية متاحة للفواتير النشطة فقط.'
                  : 'حدث خطأ أثناء إنشاء الحركة المخزنية.'}
          </AlertDescription>
        </Alert>
      )}

      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <span>{order.orderNumber}</span>
            <Badge variant="outline" className={isShipmentDoc ? 'border-amber-300 bg-amber-50 text-amber-900' : 'border-slate-300 bg-slate-50 text-slate-900'}>
              {isShipmentDoc
                ? (tPurchases.shipmentDocLabel ?? 'ارسالية')
                : (tPurchases.purchaseInvoice ?? 'فاتورة مشتريات')}
            </Badge>
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="grid grid-cols-1 md:grid-cols-3 gap-3 text-sm">
            <div><span className="text-muted-foreground">{tPurchases.supplierName ?? "اسم المورد"}: </span>{supplier?.name || order.supplierName || order.supplierId}</div>
            <div><span className="text-muted-foreground">{tPurchases.date ?? "التاريخ"}: </span>{formatDateDDMMYYYY(order.date)}</div>
            <div><span className="text-muted-foreground">{tPurchases.total ?? "الإجمالي"}: </span>{formatAmount(order.grandTotal, order.currencyCode)}</div>
            <div><span className="text-muted-foreground">{tPurchases.postingStatus ?? "حالة الترحيل"}: </span>{getPostingStatusBadge(order.postingStatus)}</div>
            <div><span className="text-muted-foreground">{tPurchases.status ?? "الحالة"}: </span>{getStatusBadge(order.status)}</div>
            <div><span className="text-muted-foreground">{tPurchases.itemCount ?? "عدد الأصناف"}: </span>{order.items.length}</div>
          </div>

          <PurchaseHistoryActions
            orderId={order.id}
            canEdit={canEdit}
            canCancel={canCancel}
            canRestore={canRestore}
            isShipmentDoc={isShipmentDoc}
            postingStatus={postingStatus}
            canAdvancePosting={canAdvancePosting}
            cancelBlockedReason={cancelBlockedReason}
            t={tPurchases}
            tGlobal={tGlobal}
          />

          {(canCreateWorkTaskOnDemand || canCreateManualInventoryEffect) && (
            <div className="flex flex-wrap items-center gap-2 rounded-md border border-amber-300 bg-amber-50 p-3">
              {canCreateWorkTaskOnDemand && (
                <form action={handleCreateWorkTaskFromPurchaseOrder}>
                  <input type="hidden" name="purchaseOrderId" value={order.id} />
                  <input type="hidden" name="returnPath" value={`/admin/purchases/view/${order.id}`} />
                  <button
                    type="submit"
                    className="inline-flex items-center rounded-md border border-amber-400 bg-amber-100 px-3 py-1.5 text-xs font-medium text-amber-900 hover:bg-amber-200 cursor-pointer"
                  >
                    {tPurchases.createWorkTaskBtn ?? 'إنشاء مهمة عمل'}
                  </button>
                </form>
              )}

              {canCreateManualInventoryEffect && (
                <form action={handleCreateManualPurchaseInventoryEffect}>
                  <input type="hidden" name="purchaseOrderId" value={order.id} />
                  <input type="hidden" name="returnPath" value={`/admin/purchases/view/${order.id}`} />
                  <button
                    type="submit"
                    className="inline-flex items-center rounded-md border border-sky-400 bg-sky-100 px-3 py-1.5 text-xs font-medium text-sky-900 hover:bg-sky-200 cursor-pointer"
                  >
                    {tPurchases.createManualInventoryEffectBtn ?? 'إنشاء حركة مخزنية'}
                  </button>
                </form>
              )}
            </div>
          )}

        </CardContent>
      </Card>

      {pendingCancelledTransferDocs.length > 0 && (
        <Card className="border-amber-300 bg-amber-50">
          <CardHeader>
            <CardTitle className="text-amber-900">تنبيه على سندات التحويل الملغاة</CardTitle>
          </CardHeader>
          <CardContent className="space-y-2 text-sm text-amber-900">
            <div>
              {pendingCancelledTransferDocs.length > 1
                ? `يوجد ${pendingCancelledTransferDocs.length} سند تحويل ملغى مرتبط بهذه الفاتورة وما زال بحاجة إلى إنشاء مهمة عمل. لتفادي التكرار، نعرض أحدث سند فقط.`
                : 'يوجد سند تحويل ملغى مرتبط بهذه الفاتورة. تم عكس الأثر المخزني للسند الملغى تلقائياً.'}
            </div>
            {workTaskError === 'locked' && (
              <div className="rounded-md border border-red-300 bg-red-50 px-2 py-1 text-xs text-red-800">
                لا يمكن إنشاء المهمة الآن، المستند قيد المعالجة حالياً بواسطة المستخدم: {lockedBy || 'مستخدم آخر'}.
              </div>
            )}
            <div className="flex flex-wrap gap-2">
              {latestPendingCancelledTransferDoc && (
                <div className="flex flex-wrap items-center gap-2 rounded-md border border-amber-300 bg-white px-2 py-1">
                    <Link
                      href={`/admin/data/internal-transfers/${encodeURIComponent(latestPendingCancelledTransferDoc.id)}`}
                      className="text-xs underline"
                    >
                      {latestPendingCancelledTransferDoc.transferNumber || latestPendingCancelledTransferDoc.id}
                    </Link>
                    <form action={handleCreateWorkTaskFromPurchaseOrder}>
                      <input type="hidden" name="purchaseOrderId" value={order.id} />
                      <input type="hidden" name="cancelledTransferDocId" value={latestPendingCancelledTransferDoc.id} />
                      <input type="hidden" name="returnPath" value={`/admin/purchases/view/${order.id}`} />
                      <button
                        type="submit"
                        className="inline-flex items-center rounded-md border border-amber-400 bg-amber-50 px-2 py-0.5 text-xs font-medium hover:bg-amber-100 cursor-pointer"
                      >
                        إنشاء مهمة عمل جديدة
                      </button>
                    </form>
                  </div>
              )}
            </div>
          </CardContent>
        </Card>
      )}

      {/* Payment Details Card */}
      {(!isShipmentDoc) && (
        <Card>
          <CardHeader>
            <CardTitle>{tPurchases.paymentDetailsTitle ?? "تفاصيل الدفع"}</CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            {/* Totals summary */}
            <div className="grid grid-cols-1 md:grid-cols-3 gap-3 text-sm">
              <div>
                <span className="text-muted-foreground">{tPurchases.grandTotalLabel ?? "إجمالي الفاتورة"}: </span>
                <span className="font-semibold">{formatAmount(order.grandTotal, order.currencyCode)}</span>
              </div>
              <div>
                <span className="text-muted-foreground">{tPurchases.amountPaidLabel ?? "المبلغ المدفوع"}: </span>
                <span className={`font-semibold ${order.amountPaid > 0 ? 'text-green-700' : ''}`}>
                  {formatAmount(order.amountPaid, order.currencyCode)}
                </span>
              </div>
              <div>
                <span className="text-muted-foreground">{tPurchases.amountDueLabel ?? "المبلغ المتبقي"}: </span>
                <span className={`font-semibold ${order.amountDue > 0 ? 'text-red-700' : 'text-green-700'}`}>
                  {formatAmount(order.amountDue, order.currencyCode)}
                </span>
              </div>
            </div>

            {/* Payment methods breakdown */}
            {Array.isArray(order.paymentMethods) && order.paymentMethods.length > 0 ? (
              <div className="space-y-4">
                {order.paymentMethods.map((pm) => {
                  const methodLabel =
                    pm.method === 'cash' ? (tPurchases.methodCash ?? 'نقداً') :
                    pm.method === 'check' ? (tPurchases.methodCheck ?? 'شيك') :
                    pm.method === 'bank_transfer' ? (tPurchases.methodBankTransfer ?? 'تحويل بنكي') :
                    pm.method === 'credit' ? (tPurchases.methodCredit ?? 'آجل') :
                    pm.method;
                  const checkSourceLabel =
                    pm.checkSource === 'issued' ? (tPurchases.checkSourceIssued ?? 'صادر') :
                    pm.checkSource === 'incoming' ? (tPurchases.checkSourceIncoming ?? 'وارد') :
                    '';

                  // Resolve incoming checks
                  const resolvedIncomingChecks = (pm.method === 'check' && pm.checkSource === 'incoming' && Array.isArray(pm.incomingCheckIds) && pm.incomingCheckIds.length > 0)
                    ? pm.incomingCheckIds.map((cid) => checksReceived.find((c: any) => c.id === cid)).filter(Boolean)
                    : [];

                  return (
                    <div key={pm.id} className="rounded-md border p-3 space-y-3">
                      {/* Row: method badge + amount + currency + bank */}
                      <div className="flex flex-wrap items-center gap-4 text-sm">
                        <Badge variant="outline">{methodLabel}</Badge>
                        {checkSourceLabel && (
                          <span className="text-xs text-muted-foreground rounded bg-muted px-1.5 py-0.5">{checkSourceLabel}</span>
                        )}
                        <span className="font-semibold">{formatAmount(pm.amount, pm.currencyCode || order.currencyCode)}</span>
                        <span className="text-muted-foreground">{(pm.currencyCode || order.currencyCode || '').trim()}</span>
                        {pm.bankName && <span className="text-muted-foreground">{pm.bankName}</span>}
                        {/* Issued check details */}
                        {pm.method === 'check' && pm.checkSource === 'issued' && pm.checkNumber && (
                          <span className="text-muted-foreground">#{pm.checkNumber}</span>
                        )}
                        {pm.method === 'check' && pm.checkSource === 'issued' && pm.checkDate && (
                          <span className="text-muted-foreground">{formatDateDDMMYYYY(pm.checkDate)}</span>
                        )}
                        {pm.reference && (
                          <span className="text-muted-foreground">({pm.reference})</span>
                        )}
                      </div>

                      {/* Incoming checks detail table */}
                      {resolvedIncomingChecks.length > 0 && (
                        <div className="relative w-full overflow-auto rounded border bg-muted/20">
                          <Table>
                            <TableHeader>
                              <TableRow>
                                <TableHead className="text-xs">{tPurchases.checkNumber ?? "رقم الشيك"}</TableHead>
                                <TableHead className="text-xs">{tPurchases.checkDate ?? "تاريخ الشيك"}</TableHead>
                                <TableHead className="text-xs">{tPurchases.bankLabel ?? "البنك"}</TableHead>
                                <TableHead className="text-xs">{tPurchases.customerName ?? "العميل"}</TableHead>
                                <TableHead className="text-xs">{tPurchases.amount ?? "المبلغ"}</TableHead>
                                <TableHead className="text-xs">{tPurchases.status ?? "الحالة"}</TableHead>
                                <TableHead className="text-xs">الحالة الإدارية</TableHead>
                              </TableRow>
                            </TableHeader>
                            <TableBody>
                              {resolvedIncomingChecks.map((chk: any) => (
                                <TableRow key={chk.id}>
                                  <TableCell className="text-xs font-medium">{chk.checkNumber || '-'}</TableCell>
                                  <TableCell className="text-xs">{chk.checkDate ? formatDateDDMMYYYY(chk.checkDate) : '-'}</TableCell>
                                  <TableCell className="text-xs">{chk.bankName || '-'}</TableCell>
                                  <TableCell className="text-xs">{chk.customerName || '-'}</TableCell>
                                  <TableCell className="text-xs font-semibold">{formatAmount(chk.amount, chk.currency)}</TableCell>
                                  <TableCell className="text-xs">
                                    <Badge variant="outline" className="text-[10px]">{chk.status || '-'}</Badge>
                                  </TableCell>
                                  <TableCell className="text-xs">
                                    {chk.reservationStatus === 'endorsed' && (
                                      <Badge className="bg-green-50 text-green-900 border-green-300 text-[10px]">مجيّر</Badge>
                                    )}
                                    {chk.reservationStatus === 'reserved' && (
                                      <Badge variant="outline" className="bg-amber-50 text-amber-900 border-amber-300 text-[10px]">محجوز</Badge>
                                    )}
                                    {chk.reservationStatus !== 'endorsed' && chk.reservationStatus !== 'reserved' && (
                                      <Badge variant="outline" className="text-[10px]">متاح</Badge>
                                    )}
                                  </TableCell>
                                </TableRow>
                              ))}
                            </TableBody>
                          </Table>
                        </div>
                      )}
                    </div>
                  );
                })}
              </div>
            ) : (
              <div className="text-sm text-muted-foreground">
                {tPurchases.noPaymentMethods ?? 'لم يتم تحديد طريقة دفع.'}
              </div>
            )}
          </CardContent>
        </Card>
      )}

      <Card>
        <CardHeader>
          <CardTitle>{tPurchases.itemsTitle ?? "بنود الفاتورة"}</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="relative w-full overflow-auto">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>{tPurchases.item ?? "الصنف"}</TableHead>
                  <TableHead>{tPurchases.quantity ?? "الكمية"}</TableHead>
                  <TableHead>{tPurchases.price ?? "السعر"}</TableHead>
                  <TableHead>{tPurchases.warehouseLabel ?? "المستودع"}</TableHead>
                  <TableHead>{tPurchases.shelfLabel ?? "الرف"}</TableHead>
                  <TableHead>{tPurchases.lineDiscountPercent ?? "خصم %"}</TableHead>
                  <TableHead>{tPurchases.lineDiscountAmount ?? "خصم"}</TableHead>
                  <TableHead>{tPurchases.taxLabel ?? "ضريبة %"}</TableHead>
                  <TableHead>{tPurchases.taxAmount ?? "قيمة الضريبة"}</TableHead>
                  <TableHead>{tPurchases.bonus ?? "بونص"}</TableHead>
                  <TableHead className="text-right">{tPurchases.total ?? "الإجمالي"}</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {order.items.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={11} className="text-center text-muted-foreground py-6">
                      {tPurchases.noItems ?? "لا توجد أصناف"}
                    </TableCell>
                  </TableRow>
                ) : (
                  order.items.map((item, index) => (
                    <TableRow key={`${item.materialId}-${index}`}>
                      <TableCell>{materialName(item.materialId)}</TableCell>
                      <TableCell>{item.quantity}</TableCell>
                      <TableCell>{formatAmount(item.unitPrice, order.currencyCode)}</TableCell>
                      <TableCell>{resolveWarehouseName(item.warehouseId || order.warehouseId)}</TableCell>
                      <TableCell>{resolveShelfName(item.warehouseId || order.warehouseId, item.shelfId)}</TableCell>
                      <TableCell>{typeof item.lineDiscountPercent === 'number' ? `${item.lineDiscountPercent}%` : '-'}</TableCell>
                      <TableCell>{typeof item.lineDiscountAmount === 'number' ? formatAmount(item.lineDiscountAmount, order.currencyCode) : '-'}</TableCell>
                      <TableCell>{typeof item.taxRate === 'number' ? `${item.taxRate}%` : '-'}</TableCell>
                      <TableCell>{typeof item.taxAmount === 'number' ? formatAmount(item.taxAmount, order.currencyCode) : '-'}</TableCell>
                      <TableCell>{typeof item.bonus === 'number' ? item.bonus : '-'}</TableCell>
                      <TableCell className="text-right">{formatAmount(item.total || (item.quantity * item.unitPrice), order.currencyCode)}</TableCell>
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          </div>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>{tPurchases.attachedDocuments ?? 'الوثائق المرفقة'}</CardTitle>
        </CardHeader>
        <CardContent>
          {!order.documents || order.documents.length === 0 ? (
            <div className="text-sm text-muted-foreground">{tPurchases.noAttachedDocuments ?? 'لا توجد وثائق مرفقة.'}</div>
          ) : (
            <div className="flex flex-wrap gap-2">
              {order.documents.map((doc) => (
                <Link
                  key={doc.id}
                  href={`/api/admin/purchases/documents?filePath=${encodeURIComponent(doc.filePath)}&name=${encodeURIComponent(doc.name)}`}
                  className="inline-flex max-w-[320px] items-center rounded-md border bg-muted/20 px-3 py-1.5 text-sm text-primary underline"
                  target="_blank"
                >
                  {doc.name}
                </Link>
              ))}
            </div>
          )}
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>{tPurchases.notesTabLabel ?? 'ملاحظات'}</CardTitle>
        </CardHeader>
        <CardContent>
          {String(order.notes || '').trim() ? (
            <div className="whitespace-pre-wrap rounded-md border bg-muted/20 p-3 text-sm leading-6">
              {order.notes}
            </div>
          ) : (
            <div className="text-sm text-muted-foreground">{tPurchases.noNotes ?? 'لا توجد ملاحظات على هذه الفاتورة.'}</div>
          )}
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>{tPurchases.subsequentActionsTitle ?? "الإجراءات اللاحقة على الفاتورة"}</CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="grid grid-cols-2 md:grid-cols-6 gap-2 text-sm">
            <div className="rounded-md border p-2 text-center"><div className="text-muted-foreground">{tPurchases.transferDocEvent ?? "إرساليات"}</div><div className="font-semibold">{transferDocs.length}</div></div>
            <div className="rounded-md border p-2 text-center"><div className="text-muted-foreground">{tPurchases.supplierPaymentEvent ?? "سندات دفع"}</div><div className="font-semibold">{linkedPayments.length}</div></div>
            <div className="rounded-md border p-2 text-center"><div className="text-muted-foreground">{tPurchases.purchaseReturnEvent ?? "مردودات"}</div><div className="font-semibold">{returns.length}</div></div>
            <div className="rounded-md border p-2 text-center"><div className="text-muted-foreground">{tPurchases.shipmentEvent ?? "شحنات"}</div><div className="font-semibold">{shipments.length}</div></div>
            <div className="rounded-md border p-2 text-center"><div className="text-muted-foreground">{tPurchases.inventoryMovementEvent ?? "حركات مخزنية"}</div><div className="font-semibold">{inventoryMovements.length}</div></div>
            <div className="rounded-md border p-2 text-center"><div className="text-muted-foreground">{tPurchases.journalEvent ?? "قيود"}</div><div className="font-semibold">{journalEntries.length}</div></div>
          </div>

          <div className="relative w-full overflow-auto">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>{tPurchases.date ?? "التاريخ"}</TableHead>
                  <TableHead>{tPurchases.actionType ?? "نوع الإجراء"}</TableHead>
                  <TableHead>{tPurchases.reference ?? "المرجع"}</TableHead>
                  <TableHead>{tPurchases.status ?? "الحالة"}</TableHead>
                  <TableHead>{tPurchases.details ?? "التفاصيل"}</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {events.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={5} className="text-center text-muted-foreground py-6">
                      {tPurchases.noSubsequentActions ?? "لا توجد إجراءات لاحقة على هذه الفاتورة."}
                    </TableCell>
                  </TableRow>
                ) : (
                  events.map((event, index) => (
                    <TableRow key={`${event.type}-${event.reference}-${index}`}>
                      <TableCell>{event.date ? formatDateTimeDDMMYYYY(event.date) : "-"}</TableCell>
                      <TableCell>{event.type}</TableCell>
                      <TableCell>
                        {event.href ? (
                          <Link href={event.href} className="underline text-primary">
                            {event.reference || "-"}
                          </Link>
                        ) : (event.reference || "-")}
                      </TableCell>
                      <TableCell>{event.status || "-"}</TableCell>
                      <TableCell>{event.details || "-"}</TableCell>
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          </div>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>{tPurchases.logTabLabel ?? 'log'}</CardTitle>
        </CardHeader>
        <CardContent>
          {!Array.isArray(order.activityLog) || order.activityLog.length === 0 ? (
            <div className="text-sm text-muted-foreground">{tPurchases.noActivityLog ?? 'لا توجد عمليات مسجلة على هذه الفاتورة.'}</div>
          ) : (
            <div className="space-y-2">
              {[...order.activityLog]
                .sort((a, b) => new Date(b.at || 0).getTime() - new Date(a.at || 0).getTime())
                .map((entry) => (
                  <div key={entry.id} className="rounded-md border p-3">
                    <div className="mb-1 flex flex-wrap items-center justify-between gap-2">
                      <span className="text-xs font-medium uppercase">{entry.action}</span>
                      <span className="text-[11px] text-muted-foreground">{entry.at ? formatDateTimeDDMMYYYY(entry.at) : '-'}</span>
                    </div>
                    <div className="whitespace-pre-wrap font-mono text-xs leading-5">{entry.message}</div>
                    {entry.by ? <div className="mt-1 text-[11px] text-muted-foreground">{entry.by}</div> : null}
                  </div>
                ))}
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
