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 { ApprovalsSearch } from "./approvals-search";
import { Suspense } from "react";
import type { Metadata } from "next";

export const metadata: Metadata = { title: "Approvals" };

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

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

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

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

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

  if (q?.trim()) {
    where.OR = [
      { poNumber: { contains: q.trim(), mode: "insensitive" } },
      { submitter: { name: { contains: q.trim(), mode: "insensitive" } } },
      { title: { contains: q.trim(), mode: "insensitive" } },
    ];
  }
  if (vesselId) where.vesselId = vesselId;
  if (dateFrom) where.submittedAt = { gte: new Date(dateFrom) };

  const [pending, vessels] = await Promise.all([
    db.purchaseOrder.findMany({
      where,
      include: { submitter: true, vessel: true, account: true },
      orderBy: { submittedAt: "asc" },
    }),
    db.vessel.findMany({ orderBy: { name: "asc" }, select: { id: true, name: true } }),
  ]);

  return (
    <div>
      <div className="mb-4">
        <h1 className="text-2xl font-semibold text-neutral-900">Approval Queue</h1>
        <p className="mt-1 text-sm text-neutral-500">
          {pending.length} order{pending.length !== 1 ? "s" : ""} awaiting your decision
        </p>
      </div>

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

      {pending.length === 0 ? (
        <div className="rounded-lg border border-neutral-200 bg-white p-12 text-center">
          <p className="text-neutral-500">No purchase orders awaiting approval.</p>
        </div>
      ) : (
        <>
          {/* ── Desktop table ─────────────────────────────────────────── */}
          <div className="hidden md:block 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">Submitter</th>
                  <th className="px-4 py-3 text-left font-medium text-neutral-600">Cost Centre</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">Submitted</th>
                  <th className="px-4 py-3"></th>
                </tr>
              </thead>
              <tbody className="divide-y divide-neutral-100">
                {pending.map((po) => (
                  <tr key={po.id} className="hover:bg-neutral-50">
                    <td className="px-4 py-3 font-mono text-xs text-neutral-600">{po.poNumber}</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.submitter.name}</td>
                    <td className="px-4 py-3 text-neutral-600">{po.vessel.name}</td>
                    <td className="px-4 py-3 text-right font-mono text-sm">
                      {formatCurrency(Number(po.totalAmount), po.currency)}
                    </td>
                    <td className="px-4 py-3 text-neutral-500">
                      {po.submittedAt ? formatDate(po.submittedAt) : "—"}
                    </td>
                    <td className="px-4 py-3">
                      <Link href={`/approvals/${po.id}`} className="text-primary-600 hover:text-primary-700 font-medium">
                        Review →
                      </Link>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>

          {/* ── Mobile cards ──────────────────────────────────────────── */}
          <div className="md:hidden space-y-3">
            {pending.map((po) => (
              <Link key={po.id} href={`/approvals/${po.id}`} className="block">
                <div className="rounded-xl border border-neutral-200 bg-white p-4 shadow-sm active:bg-neutral-50 transition-colors">
                  <div className="flex items-start justify-between gap-2 mb-1">
                    <span className="font-mono text-xs text-neutral-500">{po.poNumber}</span>
                    <span className="text-xs text-neutral-400 shrink-0">
                      {po.submittedAt ? formatDate(po.submittedAt) : "—"}
                    </span>
                  </div>
                  <p className="font-semibold text-neutral-900 leading-snug mb-2">{po.title}</p>
                  <div className="flex items-center justify-between text-sm">
                    <span className="text-neutral-500 truncate max-w-[55%]">
                      {po.submitter.name} · {po.vessel.name}
                    </span>
                    <span className="font-mono font-semibold text-neutral-900 shrink-0">
                      {formatCurrency(Number(po.totalAmount), po.currency)}
                    </span>
                  </div>
                  <div className="mt-3">
                    <span className="block w-full rounded-lg bg-primary-600 py-2 text-center text-sm font-semibold text-white">
                      Review →
                    </span>
                  </div>
                </div>
              </Link>
            ))}
          </div>
        </>
      )}
    </div>
  );
}
