import { auth } from "@/auth";
import { db } from "@/lib/db";
import { notFound, redirect } from "next/navigation";
import { ReceiptForm } from "./receipt-form";
import type { Metadata } from "next";

export const metadata: Metadata = { title: "Confirm Receipt" };

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

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

  const { id } = await params;

  const po = await db.purchaseOrder.findUnique({
    where: { id },
    select: {
      id: true,
      poNumber: true,
      title: true,
      status: true,
      submitterId: true,
      paidAmount: true,
      totalAmount: true,
      lineItems: {
        orderBy: { sortOrder: "asc" },
        select: {
          id: true,
          name: true,
          quantity: true,
          unit: true,
          deliveredQuantity: true,
        },
      },
    },
  });

  if (!po) notFound();
  if (
    po.status !== "PAID_DELIVERED" &&
    po.status !== "PARTIALLY_CLOSED" &&
    po.status !== "PARTIALLY_PAID"
  ) {
    redirect(`/po/${id}`);
  }
  if (po.submitterId !== session.user.id && session.user.role !== "SUPERUSER") {
    redirect(`/po/${id}`);
  }

  const lineItems = po.lineItems.map((li) => ({
    id: li.id,
    name: li.name,
    quantity: Number(li.quantity),
    unit: li.unit,
    deliveredQuantity: li.deliveredQuantity !== null ? Number(li.deliveredQuantity) : null,
  }));

  const isPartiallyReceived = po.status === "PARTIALLY_CLOSED";
  const isPartiallyPaid = po.status === "PARTIALLY_PAID";

  return (
    <div className="max-w-2xl">
      <div className="mb-6">
        <h1 className="text-2xl font-semibold text-neutral-900">
          {isPartiallyReceived ? "Confirm Remaining Receipt" : "Confirm Receipt"}
        </h1>
        <p className="mt-1 text-sm text-neutral-500">
          {po.poNumber} — {po.title}
        </p>
        {isPartiallyReceived && (
          <p className="mt-2 text-sm text-amber-700 bg-amber-50 border border-amber-200 rounded-lg px-3 py-2">
            This PO has been partially received. Mark the quantities delivered in this batch.
          </p>
        )}
      </div>
      <ReceiptForm
        poId={po.id}
        lineItems={lineItems}
        isPartiallyReceived={isPartiallyReceived}
        isPartiallyPaid={isPartiallyPaid}
        paidAmount={po.paidAmount != null ? Number(po.paidAmount) : undefined}
        totalAmount={Number(po.totalAmount)}
      />
    </div>
  );
}
