import { auth } from "@/auth";
import { db } from "@/lib/db";
import { hasPermission } from "@/lib/permissions";
import { notFound, redirect } from "next/navigation";
import { ApprovalActions } from "./approval-actions";
import { PoDetail } from "@/components/po/po-detail";
import { ManagerEditPoForm } from "./manager-edit-po-form";
import type { Metadata } from "next";

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

export const metadata: Metadata = { title: "Review PO" };

export default async function ApprovalDetailPage({ params }: Props) {
  const session = await auth();
  if (!session?.user) redirect("/login");

  if (!hasPermission(session.user.role, "approve_po")) redirect("/dashboard");

  const { id } = await params;

  const [po, vessels, accounts, vendors] = await Promise.all([
    db.purchaseOrder.findUnique({
      where: { id },
      include: {
        submitter: true,
        vessel: true,
        account: true,
        vendor: true,
        lineItems: { orderBy: { sortOrder: "asc" } },
        documents: { orderBy: { uploadedAt: "desc" } },
        actions: { include: { actor: true }, orderBy: { createdAt: "asc" } },
        receipt: true,
      },
    }),
    db.vessel.findMany({ where: { isActive: true }, orderBy: { name: "asc" } }),
    db.account.findMany({ where: { isActive: true }, orderBy: { name: "asc" } }),
    db.vendor.findMany({ where: { isActive: true }, orderBy: { name: "asc" } }),
  ]);

  if (!po) notFound();
  if (po.status !== "MGR_REVIEW") redirect(`/po/${id}`);

  const serializedPo = {
    ...po,
    totalAmount: po.totalAmount.toNumber(),
    lineItems: po.lineItems.map((li) => ({
      ...li,
      quantity: li.quantity.toNumber(),
      unitPrice: li.unitPrice.toNumber(),
      totalPrice: li.totalPrice.toNumber(),
      gstRate: li.gstRate.toNumber(),
    })),
  };

  return (
    <div className="max-w-6xl">
      <div className="mb-6 flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-semibold text-neutral-900">Review Purchase Order</h1>
          <p className="mt-1 text-sm text-neutral-500">{po.poNumber} — {po.title}</p>
        </div>
      </div>

      {!po.vendorId && (
        <div className="mb-4 rounded-lg border border-danger-100 bg-danger-50 px-4 py-3">
          <p className="text-sm font-medium text-danger-700">Vendor required before approval</p>
          <p className="text-sm text-danger-600 mt-0.5">
            This PO has no vendor assigned. Use &ldquo;Request Vendor ID&rdquo; to route it for vendor selection, or assign a vendor via the Edit PO form.
          </p>
        </div>
      )}

      <PoDetail po={po} currentUserId={session.user.id} currentRole={session.user.role} readOnly />

      <ManagerEditPoForm
        po={serializedPo}
        vessels={vessels}
        accounts={accounts}
        vendors={vendors}
      />

      <div className="mt-6">
        <ApprovalActions poId={po.id} poStatus={po.status} />
      </div>
    </div>
  );
}
