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

import PurchaseReturnDetailActions from "@/components/admin/purchase-return-detail-actions";
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 { getCurrentLocale, getTranslations } from "@/lib/i18n";

export default async function PurchaseReturnDetailPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const session = await verifySession();
  if (!session?.user || session.user.role !== "admin") return notFound();

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

  let ret = undefined;
  let suppliers = [];
  let materials = [];
  let order = undefined;

  
  const { pgGetPurchaseReturns, pgGetSuppliers, pgGetMaterials, pgGetPurchaseOrders } = await import('@/lib/postgres/data-access');
  const [returnsResult, suppliersResult, materialsResult, purchaseOrdersResult] = await Promise.all([
  pgGetPurchaseReturns({ page: 1, pageSize: 5000 }),
  pgGetSuppliers({ page: 1, pageSize: 5000 }),
  pgGetMaterials({ page: 1, pageSize: 5000 }),
  pgGetPurchaseOrders({ page: 1, pageSize: 5000 }),
  ]);

  ret = ((returnsResult.items || []) as any[]).find((entry) => entry.id === id) || ret;
  suppliers = (suppliersResult.items || []) as typeof suppliers;
  materials = (materialsResult.items || []) as typeof materials;

  if (ret) {
  order = ((purchaseOrdersResult.items || []) as any[]).find(
    (entry) => entry.id === ret!.purchaseOrderId
  );
  }
  

  if (!ret) return notFound();

  const supplier = suppliers.find((s) => s.id === ret.supplierId);

  const money = (val: number) => new Intl.NumberFormat('en-US', { style: 'currency', currency: ret.currencyCode || 'USD' }).format(val || 0);
  const materialName = (id: string) => materials.find((m) => m.id === id)?.name || id;
  const shortDate = (val: any) => {
    try {
      return new Date(val).toISOString().slice(0, 10);
    } catch {
      return '';
    }
  };

  const statusBadge = ret.status === 'cancelled'
    ? <Badge variant="outline" className="text-destructive border-destructive">{ret.status}</Badge>
    : <Badge>{ret.status}</Badge>;

  return (
    <div dir={isRtl ? 'rtl' : 'ltr'} className={`space-y-4 ${isRtl ? 'text-right' : 'text-left'}`}>
      <div className="flex justify-between items-center">
        <h1 className="text-2xl font-semibold">{tPurchases.purchaseReturnsTab ?? 'مردودات المشتريات'}</h1>
        <Link href="/admin/purchases/returns" className="text-sm underline">{tGlobal.back || 'رجوع'}</Link>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>{tPurchases.returnNumber || 'رقم المردود'}: {ret.returnNumber}</CardTitle>
        </CardHeader>
        <CardContent className="space-y-3 text-sm">
          <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
            <div><span className="text-muted-foreground">{tPurchases.supplier || 'المورد'}:</span> {supplier?.name || ret.supplierId}</div>
            <div><span className="text-muted-foreground">{tPurchases.order || 'الفاتورة'}:</span> {order?.orderNumber || ret.purchaseOrderId}</div>
            <div><span className="text-muted-foreground">{tPurchases.date || 'التاريخ'}:</span> {shortDate(ret.createdAt)}</div>
            <div><span className="text-muted-foreground">{tPurchases.status || 'الحالة'}:</span> {statusBadge}</div>
            <div><span className="text-muted-foreground">{tPurchases.total || 'الإجمالي'}:</span> {money(ret.totalAmount)}</div>
            <div><span className="text-muted-foreground">{tPurchases.currencyLabel || 'العملة'}:</span> {ret.currencyCode || '-'}</div>
          </div>
          <div className="flex justify-end">
            <PurchaseReturnDetailActions returnId={ret.id} isCancelled={ret.status === 'cancelled'} t={tPurchases} />
          </div>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>{tPurchases.items || 'الأصناف'}</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="relative w-full overflow-auto">
            <Table className="w-full table-fixed text-sm [&_th]:border-s [&_th]:border-border/70 [&_th:first-child]:border-s-0 [&_td]:border-s [&_td]:border-border/40 [&_td:first-child]:border-s-0 [&_th]:p-2 [&_td]:p-2 [&_th]:bg-muted/40 [&_th]:text-xs [&_th]:font-medium [&_td]:align-middle">
              <TableHeader>
                <TableRow>
                  <TableHead className="text-center">{tPurchases.item || 'الصنف'}</TableHead>
                  <TableHead className="text-center">{tPurchases.qty || 'الكمية'}</TableHead>
                  <TableHead className="text-center">{tPurchases.returnUnitPrice || 'سعر المرتجع'}</TableHead>
                  <TableHead className="text-center">{tPurchases.total || 'الإجمالي'}</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {ret.items.length === 0 ? (
                  <TableRow><TableCell colSpan={4} className="text-center text-muted-foreground">{tPurchases.noItems || 'لا توجد أصناف'}</TableCell></TableRow>
                ) : ret.items.map((it) => (
                  <TableRow key={it.id}>
                    <TableCell className="text-center">{materialName(it.materialId)}</TableCell>
                    <TableCell className="text-center">{it.quantity}</TableCell>
                    <TableCell className="text-center">{money(it.costPerUnitOriginal)}</TableCell>
                    <TableCell className="text-center">{money(it.amount)}</TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
