import { getTranslations, getCurrentLocale } from "@/lib/i18n";

import { pgGetDefaultCurrency, pgGetInternalTransfers, pgGetPurchaseOrders } from "@/lib/postgres/data-access";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { format } from "date-fns";
import { Badge } from "@/components/ui/badge";
import { getCurrencySymbolAsync } from "@/lib/server-currency";
import { formatCurrency as formatCurrencyUtil } from "@/lib/currency-formatter";
import Link from "next/link";
import { Input } from "@/components/ui/input";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import PurchaseHistoryContextRow from "@/components/admin/purchase-history-context-row";

type PurchaseHistoryPageProps = {
  searchParams?: Promise<Record<string, string | string[] | undefined>>;
};

export default async function PurchaseHistoryPage({ searchParams }: PurchaseHistoryPageProps) {
  const locale = await getCurrentLocale();
  const t = getTranslations(locale);
  const tPurchases = t.Purchases ?? {};
  const params = (await searchParams) ?? {};

  const page = Number(Array.isArray(params.page) ? params.page[0] : params.page) || 1;
  const pageSize = Number(Array.isArray(params.pageSize) ? params.pageSize[0] : params.pageSize) || 25;
  const search = String(Array.isArray(params.search) ? params.search[0] : (params.search || '')).trim();
  const duplicateError = String(Array.isArray(params.duplicateError) ? params.duplicateError[0] : (params.duplicateError || '')).trim();

  const purchaseHistory = await pgGetPurchaseOrders({ page, pageSize, search }) as any;
  const internalTransferDocs = (await pgGetInternalTransfers({ page: 1, pageSize: 10000 })).items;
  const currencies = (await (await import('@/lib/postgres/data-access')).pgGetCurrencies({ page: 1, pageSize: 500 })).items;
  const purchaseOrders: any[] = Array.isArray(purchaseHistory.items) ? purchaseHistory.items : [];
  const defaultCurrency = await pgGetDefaultCurrency() as any;
  const defaultBaseCurrencyCode = String(defaultCurrency?.code || 'JOD');
  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 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>{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 getDocumentTypeBadge = (order: (typeof purchaseOrders)[number]) => {
    const docType = (order as any).documentType;
    if (!docType || docType === 'tax_invoice') {
      return <Badge className="ms-1.5 bg-slate-100 text-slate-800 border-slate-300 text-[10px] px-1.5 py-0" variant="outline">{tPurchases.taxInvoiceBadge ?? 'ضريبية'}</Badge>;
    }
    if (docType === 'shipment') {
      const hasInvoice = Boolean((order as any).taxInvoiceId);
      if (hasInvoice) {
        return <Badge className="ms-1.5 bg-green-100 text-green-800 border-green-300 text-[10px] px-1.5 py-0" variant="outline">{tPurchases.shipmentLinkedBadge ?? 'مرتبطة'}</Badge>;
      }
      return <Badge className="ms-1.5 bg-amber-100 text-amber-800 border-amber-300 text-[10px] px-1.5 py-0" variant="outline">{tPurchases.shipmentOpenBadge ?? 'مخزنية'}</Badge>;
    }
    return null;
  };

  const getDocumentTypeLabel = (order: (typeof purchaseOrders)[number]) => {
    const docType = (order as any).documentType;
    if (docType === 'shipment') return tPurchases.shipmentDocLabel ?? 'ارسالية';
    return tPurchases.purchaseInvoice ?? 'فاتورة مشتريات';
  };

  const totalOrders = Number(purchaseHistory?.stats?.totalOrders ?? purchaseHistory?.totalItems ?? 0);
  let totalAmount = 0;
  if ('stats' in purchaseHistory) {
    totalAmount = Number((purchaseHistory.stats as Record<string, unknown>).totalAmount || 0);
  } else {
    for (const order of purchaseOrders as Array<Record<string, unknown>>) {
      totalAmount += Number(order.grandTotal || 0);
    }
  }
  const activeOrders = Number(purchaseHistory?.stats?.activeOrders ?? purchaseOrders.filter((o: any) => o.status === 'active').length);
  const allTransferDocs = Array.isArray(internalTransferDocs) ? internalTransferDocs : [];
  const transferDocsByOrderId = new Map<string, any[]>();
  const cancelledSourceTagRegex = /\[source-cancelled:([^\]]+)\]/;
  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 });
  };

  allTransferDocs.forEach((doc: any) => {
    const orderId = String(doc?.sourcePurchaseOrderId || '').trim();
    if (!orderId) return;
    const bucket = transferDocsByOrderId.get(orderId) || [];
    bucket.push(doc);
    transferDocsByOrderId.set(orderId, bucket);
  });

  const cancelledTransferOrderIds = new Set(
    Array.from(transferDocsByOrderId.entries())
      .filter(([_, docs]) => {
        const cancelledDocs = docs.filter((doc: any) => doc?.status === 'cancelled');
        if (cancelledDocs.length === 0) return false;

        const activeDocs = docs.filter((doc: any) => doc?.status === 'active');
        const recreatedCancelledDocIds = new Set(
          activeDocs
            .map((doc: any) => {
              const match = String(doc?.note || '').match(cancelledSourceTagRegex);
              return match?.[1] ? String(match[1]).trim() : '';
            })
            .filter((idValue: string) => idValue)
        );

        let unresolvedCancelled = cancelledDocs.filter(
          (doc: any) => !recreatedCancelledDocIds.has(String(doc?.id || '').trim())
        );

        const hasLegacyReplacementDoc = activeDocs.some((doc: any) => {
          const note = String(doc?.note || '');
          return note.includes('مهمة عمل لفاتورة مشتريات') || note.includes('(إعادة إنشاء)');
        });

        if (hasLegacyReplacementDoc && unresolvedCancelled.length > 0) {
          const sortedUnresolved = unresolvedCancelled.slice().sort(sortTransferDocsDesc);
          sortedUnresolved.shift();
          unresolvedCancelled = sortedUnresolved;
        }

        return unresolvedCancelled.length > 0;
      })
      .map(([orderId]) => orderId)
  );
  const ordersWithCancelledTransfer = cancelledTransferOrderIds.size;

  const resolveBaseEquivalent = (order: (typeof purchaseOrders)[number]) => {
    if (typeof order.grandTotalBase === 'number' && Number.isFinite(order.grandTotalBase)) {
      return order.grandTotalBase;
    }

    const baseCode = order.baseCurrencyCode || defaultBaseCurrencyCode;
    const currencyCode = order.currencyCode || baseCode;
    const fxRate = Number(order.exchangeRate || (currencyCode === baseCode ? 1 : 0));
    const safeRate = Number.isFinite(fxRate) && fxRate > 0 ? fxRate : 1;
    return Number(order.grandTotal || 0) * safeRate;
  };

  const resolveItemCount = (order: (typeof purchaseOrders)[number]) => {
    if (Array.isArray((order as any).items)) {
      return (order as any).items.length;
    }

    const fallback = Number((order as any).itemCount ?? 0);
    return Number.isFinite(fallback) && fallback >= 0 ? fallback : 0;
  };

  return (
    <div className="space-y-6">
      <Card>
        <CardHeader>
          <CardTitle>{tPurchases.orderHistory ?? 'سجل الأوامر'}</CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          {duplicateError && (
            <Alert className="border-red-300 bg-red-50 text-red-900">
              <AlertTitle>تعذر نسخ السند</AlertTitle>
              <AlertDescription>
                {duplicateError === 'missing_source'
                  ? 'لم يتم تحديد السند المصدر.'
                  : duplicateError === 'not_found'
                    ? 'السند المصدر غير موجود.'
                    : duplicateError === 'Unauthorized'
                      ? 'غير مصرح لك بتنفيذ هذه العملية.'
                      : `حدث خطأ أثناء النسخ: ${duplicateError}`}
              </AlertDescription>
            </Alert>
          )}

          <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
            <div className="space-y-2 rounded-md border p-4">
              <div className="text-sm text-muted-foreground">{tPurchases.totalOrders ?? 'إجمالي الأوامر'}</div>
              <div className="text-2xl font-bold">{totalOrders}</div>
            </div>
            <div className="space-y-2 rounded-md border p-4">
              <div className="text-sm text-muted-foreground">{tPurchases.activeOrders ?? 'الأوامر النشطة'}</div>
              <div className="text-2xl font-bold">{activeOrders}</div>
            </div>
            <div className="space-y-2 rounded-md border p-4">
              <div className="text-sm text-muted-foreground">{tPurchases.totalValue ?? 'القيمة الإجمالية'}</div>
              <div className="text-2xl font-bold">{formatAmount(totalAmount, defaultBaseCurrencyCode)}</div>
            </div>
            <div className="space-y-2 rounded-md border border-amber-300 bg-amber-50 p-4">
              <div className="text-sm text-amber-800">أوامر بها إرساليات ملغاة تحتاج إجراء</div>
              <div className="text-2xl font-bold text-amber-900">{ordersWithCancelledTransfer}</div>
            </div>
          </div>

          <form className="grid grid-cols-1 md:grid-cols-[1fr_auto] gap-2" method="get">
            <Input
              type="text"
              name="search"
              defaultValue={search}
              placeholder={tPurchases.searchPlaceholder ?? 'ابحث برقم الأمر أو المورد أو العملة...'}
              className="h-9"
            />
            <Button type="submit" variant="outline" className="h-9">
              {tPurchases.searchAction ?? 'بحث'}
            </Button>
          </form>

          <div className="rounded-md border">
            <div className="relative w-full overflow-auto">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>{tPurchases.orderNumber ?? 'رقم الأمر'}</TableHead>
                    <TableHead>{tPurchases.documentTypeLabel ?? 'نوع السند'}</TableHead>
                    <TableHead>{tPurchases.supplierName ?? 'اسم المورد'}</TableHead>
                    <TableHead>{tPurchases.date ?? 'التاريخ'}</TableHead>
                    <TableHead>{tPurchases.itemCount ?? 'عدد الأصناف'}</TableHead>
                    <TableHead>{tPurchases.currencyLabel ?? 'العملة'}</TableHead>
                    <TableHead className="text-right">{tPurchases.total ?? 'الإجمالي'}</TableHead>
                    <TableHead className="text-right">{tPurchases.convertedToBase ?? 'القيمة بالعملة الأساسية'}</TableHead>
                    <TableHead>{tPurchases.postingStatus ?? 'حالة الترحيل'}</TableHead>
                    <TableHead>{tPurchases.status ?? 'الحالة'}</TableHead>
                    <TableHead>{tPurchases.view ?? 'معاينة'}</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {purchaseOrders.length === 0 ? (
                    <TableRow>
                      <TableCell colSpan={11} className="text-center text-muted-foreground py-8">
                        {search ? (tPurchases.noSearchResults ?? 'لا توجد نتائج مطابقة.') : (tPurchases.noOrders ?? 'لا توجد أوامر')}
                      </TableCell>
                    </TableRow>
                  ) : (
                    purchaseOrders.map((order) => (
                      <PurchaseHistoryContextRow
                        key={order.id}
                        orderId={String(order.id)}
                        returnPath={`/admin/purchases/history?page=${page}&pageSize=${pageSize}&search=${encodeURIComponent(search)}`}
                        duplicateLabel={String((order as any).documentType || 'tax_invoice') === 'shipment'
                          ? (tPurchases.duplicateShipmentLabel ?? 'نسخ الإرسالية')
                          : (tPurchases.duplicateInvoiceLabel ?? 'نسخ الفاتورة')}
                      >
                        {(() => {
                          const baseCode = order.baseCurrencyCode || defaultBaseCurrencyCode;
                          const currencyCode = order.currencyCode || baseCode;
                          const baseEquivalent = resolveBaseEquivalent(order);

                          return (
                            <>
                        <TableCell className="font-medium">
                          <Link
                            href={`/admin/purchases/view/${order.id}`}
                            className="underline text-primary"
                            title={String((order as any).documentType || 'tax_invoice') === 'shipment'
                              ? (tPurchases.openShipment ?? 'فتح الإرسالية')
                              : (tPurchases.openInvoice ?? 'فتح الفاتورة')}
                          >
                            {order.orderNumber}
                          </Link>
                          {cancelledTransferOrderIds.has(String(order.id || '').trim()) && (
                            <Badge className="ms-1.5 bg-amber-100 text-amber-800 border-amber-300 text-[10px] px-1.5 py-0" variant="outline">
                              تحويل ملغى يحتاج إجراء
                            </Badge>
                          )}
                        </TableCell>
                        <TableCell>
                          <Badge
                            variant="outline"
                            className={String((order as any).documentType || 'tax_invoice') === 'shipment'
                              ? 'border-amber-300 bg-amber-50 text-amber-900'
                              : 'border-slate-300 bg-slate-50 text-slate-900'}
                          >
                            {getDocumentTypeLabel(order)}
                          </Badge>
                          {getDocumentTypeBadge(order)}
                        </TableCell>
                        <TableCell>{order.supplierName}</TableCell>
                        <TableCell>{format(new Date(order.date), 'yyyy-MM-dd')}</TableCell>
                        <TableCell>{resolveItemCount(order)}</TableCell>
                        <TableCell>{currencyCode}</TableCell>
                        <TableCell className="text-right">{formatAmount(order.grandTotal, currencyCode)}</TableCell>
                        <TableCell className="text-right">{formatAmount(baseEquivalent, baseCode)} ({baseCode})</TableCell>
                        <TableCell>{getPostingStatusBadge(order.postingStatus)}</TableCell>
                        <TableCell>{getStatusBadge(order.status)}</TableCell>
                        <TableCell>
                          <Button asChild size="sm" variant="outline">
                            <Link href={`/admin/purchases/view/${order.id}`}>
                              {String((order as any).documentType || 'tax_invoice') === 'shipment'
                                ? (tPurchases.openShipment ?? tPurchases.view ?? 'فتح الإرسالية')
                                : (tPurchases.openInvoice ?? tPurchases.view ?? 'فتح الفاتورة')}
                            </Link>
                          </Button>
                        </TableCell>
                            </>
                          );
                        })()}
                      </PurchaseHistoryContextRow>
                    ))
                  )}
                </TableBody>
              </Table>
            </div>
          </div>

          <div className="flex flex-wrap items-center justify-between gap-2">
            <div className="text-sm text-muted-foreground">
              {tPurchases.paginationSummary ?? 'الصفحة'} {purchaseHistory.page} / {purchaseHistory.totalPages} - {tPurchases.totalOrders ?? 'الإجمالي'} {purchaseHistory.totalItems}
            </div>
            <div className="flex items-center gap-2">
              <Button asChild variant="outline" size="sm" disabled={!purchaseHistory.hasPrev}>
                <Link href={`?page=${Math.max(1, purchaseHistory.page - 1)}&pageSize=${purchaseHistory.pageSize}&search=${encodeURIComponent(search)}`}>
                  {tPurchases.previousPage ?? 'السابق'}
                </Link>
              </Button>
              <Button asChild variant="outline" size="sm" disabled={!purchaseHistory.hasNext}>
                <Link href={`?page=${Math.min(purchaseHistory.totalPages, purchaseHistory.page + 1)}&pageSize=${purchaseHistory.pageSize}&search=${encodeURIComponent(search)}`}>
                  {tPurchases.nextPage ?? 'التالي'}
                </Link>
              </Button>
            </div>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
