import { auth } from "@/auth";
import { db } from "@/lib/db";
import { hasPermission } from "@/lib/permissions";
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 { PaymentHistoryFilters } from "./payment-history-filters";
import { Suspense } from "react";
import type { Metadata } from "next";

export const metadata: Metadata = { title: "Payment History" };

interface Props {
  searchParams: Promise<{
    dateFrom?: string;
    dateTo?: string;
    vesselId?: string;
  }>;
}

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

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

  const { dateFrom, dateTo, vesselId } = await searchParams;

  const where: NonNullable<Parameters<typeof db.purchaseOrder.findMany>[0]>["where"] = {
    status: { in: ["PAID_DELIVERED", "CLOSED"] },
  };

  if (dateFrom) where.paidAt = { ...where.paidAt as object, gte: new Date(dateFrom) };
  if (dateTo) {
    const end = new Date(dateTo);
    end.setDate(end.getDate() + 1);
    where.paidAt = { ...where.paidAt as object, lt: end };
  }
  if (vesselId) where.vesselId = vesselId;

  const [orders, vessels, totalResult] = await Promise.all([
    db.purchaseOrder.findMany({
      where,
      include: {
        submitter: true,
        vessel: true,
        account: true,
        vendor: true,
      },
      orderBy: { paidAt: "desc" },
      take: 200,
    }),
    db.vessel.findMany({ orderBy: { name: "asc" }, select: { id: true, name: true } }),
    db.purchaseOrder.aggregate({
      _sum: { totalAmount: true },
      where,
    }),
  ]);

  const totalPaid = Number(totalResult._sum.totalAmount ?? 0);

  return (
    <div>
      <div className="mb-6">
        <h1 className="text-2xl font-semibold text-neutral-900">Payment History</h1>
        <p className="mt-1 text-sm text-neutral-500">
          POs marked as paid or fully closed
        </p>
      </div>

      {/* Summary stat */}
      <div className="mb-4 rounded-lg border border-neutral-200 bg-white p-4 flex items-center justify-between">
        <div>
          <p className="text-xs font-medium text-neutral-500 uppercase tracking-wide">Total Paid</p>
          <p className="mt-0.5 text-2xl font-semibold text-neutral-900 font-mono">
            {formatCurrency(totalPaid)}
          </p>
        </div>
        <div className="text-right">
          <p className="text-xs font-medium text-neutral-500 uppercase tracking-wide">Orders</p>
          <p className="mt-0.5 text-2xl font-semibold text-neutral-900">{orders.length}</p>
        </div>
      </div>

      <Suspense>
        <PaymentHistoryFilters vessels={vessels} />
      </Suspense>

      <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">Vendor</th>
              <th className="px-4 py-3 text-left font-medium text-neutral-600">Submitter</th>
              <th className="px-4 py-3 text-left font-medium text-neutral-600">Status</th>
              <th className="px-4 py-3 text-left font-medium text-neutral-600">Payment Ref</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">Paid</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-neutral-100">
            {orders.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:text-primary-700"
                  >
                    {po.poNumber}
                  </Link>
                </td>
                <td className="px-4 py-3 font-medium text-neutral-900 max-w-xs truncate">
                  {po.title}
                </td>
                <td className="px-4 py-3 text-neutral-600">{po.vessel.name}</td>
                <td className="px-4 py-3 text-neutral-600">{po.vendor?.name ?? "—"}</td>
                <td className="px-4 py-3 text-neutral-600">{po.submitter.name}</td>
                <td className="px-4 py-3">
                  <PoStatusBadge status={po.status} />
                </td>
                <td className="px-4 py-3 font-mono text-xs text-neutral-500">
                  {po.paymentRef ?? "—"}
                </td>
                <td className="px-4 py-3 text-right font-mono text-xs font-semibold">
                  {formatCurrency(Number(po.totalAmount), po.currency)}
                </td>
                <td className="px-4 py-3 text-neutral-500">
                  {po.paidAt ? formatDate(po.paidAt) : "—"}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
        {orders.length === 0 && (
          <div className="p-12 text-center text-neutral-500">
            No paid orders found.
          </div>
        )}
      </div>

      {orders.length === 200 && (
        <p className="mt-2 text-xs text-neutral-400 text-right">
          Showing first 200 results — refine filters to narrow results.
        </p>
      )}
    </div>
  );
}
