import { auth } from "@/auth";
import { db } from "@/lib/db";
import { redirect } from "next/navigation";
import Link from "next/link";
import { formatCurrency, formatDate } from "@/lib/utils";
import { PoStatusBadge } from "@/components/po/po-status-badge";
import type { Metadata } from "next";

export const metadata: Metadata = { title: "Closed Purchase Orders" };

export default async function MyOrdersPage() {
  const session = await auth();
  if (!session?.user) redirect("/login");

  const { role, id: userId } = session.user;
  if (!["TECHNICAL", "MANNING", "MANAGER", "SUPERUSER"].includes(role)) redirect("/dashboard");

  const isManager = role === "MANAGER" || role === "SUPERUSER";

  const closed = await db.purchaseOrder.findMany({
    where: isManager
      ? { status: "CLOSED" }
      : { submitterId: userId, status: "CLOSED" },
    orderBy: { updatedAt: "desc" },
    include: {
      vessel: { select: { name: true } },
      account: { select: { name: true, code: true } },
      actions: {
        where: {
          actionType: { in: ["EDITS_REQUESTED", "REJECTED", "APPROVED", "APPROVED_WITH_NOTE"] },
          note: { not: null },
        },
        orderBy: { createdAt: "desc" },
        take: 1,
        select: { actor: { select: { name: true } } },
      },
    },
  });

  return (
    <div>
      <div className="mb-6 flex items-center justify-between">
        <h1 className="text-2xl font-semibold text-neutral-900">Closed Purchase Orders</h1>
        <Link
          href="/po/new"
          className="rounded-lg bg-primary-600 px-4 py-2.5 text-sm font-semibold text-white hover:bg-primary-700 transition-colors"
        >
          + New PO
        </Link>
      </div>

      <PoTable title="Closed Orders" rows={closed} />
      {closed.length === 0 && (
        <div className="rounded-lg border border-neutral-200 bg-white p-12 text-center">
          <p className="text-neutral-500">No closed purchase orders yet.</p>
          <Link href="/dashboard" className="mt-4 inline-block text-sm text-primary-600 hover:underline font-medium">
            View active orders on the dashboard →
          </Link>
        </div>
      )}
    </div>
  );
}

type PoRow = {
  id: string;
  poNumber: string;
  title: string;
  status: import("@prisma/client").POStatus;
  totalAmount: import("@prisma/client").Prisma.Decimal;
  vessel: { name: string };
  account: { name: string; code: string };
  updatedAt: Date;
  managerNote: string | null;
  actions: { actor: { name: string } }[];
};

function PoTable({ title, rows, className = "" }: { title: string; rows: PoRow[]; className?: string }) {
  if (rows.length === 0) return null;
  return (
    <div className={className}>
      <h2 className="text-sm font-semibold text-neutral-700 mb-3">{title}</h2>
      <div className="rounded-lg border border-neutral-200 bg-white overflow-hidden">
        <table className="w-full text-sm">
          <thead className="bg-neutral-50 border-b border-neutral-200">
            <tr>
              <th className="px-4 py-3 text-left font-medium text-neutral-600">PO Number</th>
              <th className="px-4 py-3 text-left font-medium text-neutral-600">Title</th>
              <th className="px-4 py-3 text-left font-medium text-neutral-600">Cost Centre</th>
              <th className="px-4 py-3 text-left font-medium text-neutral-600">Status</th>
              <th className="px-4 py-3 text-right font-medium text-neutral-600">Amount</th>
              <th className="px-4 py-3 text-left font-medium text-neutral-600">Updated</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-neutral-100">
            {rows.map((po) => (
              <tr key={po.id} className="hover:bg-neutral-50">
                <td className="px-4 py-3">
                  <Link href={`/po/${po.id}`} className="font-mono text-xs text-primary-600 hover:underline">
                    {po.poNumber}
                  </Link>
                </td>
                <td className="px-4 py-3">
                  <Link href={`/po/${po.id}`} className="text-neutral-900 hover:text-primary-600 font-medium">
                    {po.title}
                  </Link>
                  {po.managerNote && (
                    <p className="mt-0.5 text-xs text-warning-700 italic truncate max-w-xs">
                      {po.actions[0]?.actor.name ? `${po.actions[0].actor.name}: ` : "Note: "}{po.managerNote}
                    </p>
                  )}
                </td>
                <td className="px-4 py-3 text-neutral-600">{po.vessel.name}</td>
                <td className="px-4 py-3"><PoStatusBadge status={po.status} /></td>
                <td className="px-4 py-3 text-right font-mono text-xs">{formatCurrency(Number(po.totalAmount))}</td>
                <td className="px-4 py-3 text-neutral-500">{formatDate(po.updatedAt)}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}
