import Link from "next/link";
import { transporterApi } from "@/lib/api/transporter";
import { requireRole, requireServerToken } from "@/lib/auth/server";
import type { ApiTransporterOrder, PaginationMeta } from "@/lib/api/types";
import TripStatusFilter from "./TripStatusFilter";
import StatusBadge from "@/components/ui/StatusBadge";

type PageProps = {
  searchParams: Promise<{ page?: string; status?: string }>;
};

// Module scope: building a formatter is expensive and it has no per-row state,
// so one instance serves every render of every row.
const inr = new Intl.NumberFormat("en-IN", { style: "currency", currency: "INR", maximumFractionDigits: 0 });

function fmtINR(n: number) {
  return inr.format(n);
}


async function loadOrders(token: string, page: number, status?: string) {
  try {
    return await transporterApi.orders(token, { page, status });
  } catch {
    return { data: [] as ApiTransporterOrder[], meta: undefined as PaginationMeta | undefined };
  }
}

/**
 * Server-rendered trips list. The client version could not ask for anything
 * until `useToken` had read the cookie inside an effect — three round trips
 * after the request. Reading the same cookie during SSR means the first HTML
 * response already carries the table.
 *
 * Filter and page live in the URL now, so only the `<select>` needs client JS.
 * `RequireRole` is replaced by a server-side check on the cached user cookie:
 * the client guard could not decide until `AuthContext` hydrated, which would
 * have hidden the server-rendered rows behind a spinner anyway.
 */
export default async function TransporterOrdersPage({ searchParams }: PageProps) {
  const token = await requireServerToken("/transporter/orders");
  await requireRole(["transporter"]);

  const sp = await searchParams;
  const page = Math.max(1, Number(sp.page) || 1);
  const status = sp.status?.trim() || "";

  const { data: orders, meta } = await loadOrders(token, page, status || undefined);

  const query = (p: number) =>
    status ? `/transporter/orders?status=${status}&page=${p}` : `/transporter/orders?page=${p}`;

  return (
    <div className="space-y-4">
      <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
        <h1 className="text-2xl font-bold text-gray-900">Trips</h1>
        <TripStatusFilter value={status} />
      </div>

      {orders.length === 0 ? (
        <div className="rounded-xl bg-white p-10 text-center text-gray-500 shadow-sm ring-1 ring-gray-100">No trips found.</div>
      ) : (
        <div className="overflow-x-auto rounded-xl bg-white shadow-sm ring-1 ring-gray-100">
          <table className="w-full min-w-[640px] divide-y divide-gray-100 text-sm">
            <thead className="bg-gray-50 text-left text-xs font-semibold uppercase tracking-wide text-gray-500">
              <tr>
                <th className="px-4 py-3">Order ID</th>
                <th className="px-4 py-3">Product</th>
                <th className="px-4 py-3">Customer</th>
                <th className="px-4 py-3">Seller</th>
                <th className="px-4 py-3">Status</th>
                <th className="px-4 py-3 text-right">Transport ₹</th>
                <th className="px-4 py-3"></th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-100">
              {orders.map((o) => (
                <tr key={o.id} className="hover:bg-gray-50">
                  <td className="whitespace-nowrap px-4 py-3 font-medium text-gray-900">{o.order_id ?? o.unique_id}</td>
                  <td className="px-4 py-3 text-gray-700">{o.product?.name ?? "—"}</td>
                  <td className="px-4 py-3 text-gray-700">{o.customer?.name ?? "—"}</td>
                  <td className="px-4 py-3 text-gray-700">{o.seller?.name ?? "—"}</td>
                  <td className="px-4 py-3">
                    <StatusBadge kind="order" code={o.status_code} label={o.status_label ?? o.status} />
                  </td>
                  <td className="px-4 py-3 text-right font-semibold text-gray-900">{fmtINR(o.transport_price)}</td>
                  <td className="px-4 py-3 text-right">
                    <Link href={`/transporter/orders/${o.id}`} className="text-sm font-medium text-[#CC1414] hover:underline">View</Link>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {meta && meta.last_page > 1 && (
        <div className="flex flex-wrap items-center justify-between gap-3 rounded-xl bg-white px-4 py-3 shadow-sm ring-1 ring-gray-100">
          <span className="min-w-0 truncate text-sm text-gray-500">Page {meta.current_page} of {meta.last_page} · {meta.total} total</span>
          {/* Plain links: no client JS needed for paging. */}
          <div className="flex gap-2">
            {page > 1 ? (
              <Link href={query(page - 1)} className="rounded-md border px-4 py-2 text-sm hover:bg-gray-50">Prev</Link>
            ) : (
              <span className="rounded-md border px-4 py-2 text-sm opacity-50">Prev</span>
            )}
            {page < meta.last_page ? (
              <Link href={query(page + 1)} className="rounded-md border px-4 py-2 text-sm hover:bg-gray-50">Next</Link>
            ) : (
              <span className="rounded-md border px-4 py-2 text-sm opacity-50">Next</span>
            )}
          </div>
        </div>
      )}
    </div>
  );
}
