import Link from "next/link";
import { transporterApi } from "@/lib/api/transporter";
import { requireRole, requireServerToken } from "@/lib/auth/server";
import type { ApiTransporterEnquiry, PaginationMeta } from "@/lib/api/types";

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

const TABS = ["pending", "replied"] as const;
type Tab = (typeof TABS)[number];

async function loadEnquiries(token: string, page: number, status: Tab) {
  try {
    return await transporterApi.enquiries(token, { page, status });
  } catch {
    return { data: [] as ApiTransporterEnquiry[], meta: undefined as PaginationMeta | undefined };
  }
}

/**
 * Server-rendered: the token comes from the cookie via `requireServerToken`, so
 * the enquiries are fetched during SSR and the browser receives a populated
 * table instead of a spinner.
 *
 * The tab and the page number moved from `useState` into the URL — that is what
 * makes server fetching possible at all, and it buys shareable/bookmarkable tabs
 * for free. With no client state left the `Loader` branch is gone too: by the
 * time this HTML exists the data is already in it.
 *
 * `RequireRole` was a client guard that could not decide anything until
 * `AuthContext` had hydrated, so it would have hidden the SSR payload behind a
 * spinner. The cached user cookie gives the same answer during SSR.
 */
export default async function TransporterEnquiriesPage({ searchParams }: PageProps) {
  const token = await requireServerToken("/transporter/enquiries");
  await requireRole(["transporter"]);

  const sp = await searchParams;
  const tab: Tab = sp.status === "replied" ? "replied" : "pending";
  const page = Math.max(1, Number(sp.page) || 1);

  const { data: list, meta } = await loadEnquiries(token, page, tab);

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

  return (
    <div className="space-y-4">
      <h1 className="text-2xl font-bold text-gray-900">Enquiries</h1>

      <div className="inline-flex rounded-lg bg-white p-1 shadow-sm ring-1 ring-gray-100">
        {TABS.map((t) => (
          <Link
            key={t}
            href={`/transporter/enquiries?status=${t}`}
            className={`rounded-md px-4 py-2 text-sm font-medium capitalize ${
              tab === t ? "bg-[#CC1414] text-white" : "text-gray-700 hover:bg-gray-50"
            }`}
          >
            {t}
          </Link>
        ))}
      </div>

      {list.length === 0 ? (
        <div className="rounded-xl bg-white p-10 text-center text-gray-500 shadow-sm ring-1 ring-gray-100">
          {tab === "pending" ? "No new enquiries awaiting your quote." : "You have not responded to any enquiries yet."}
        </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">Enquiry</th>
                <th className="px-4 py-3">Product</th>
                <th className="px-4 py-3">Origin</th>
                <th className="px-4 py-3">Status</th>
                <th className="px-4 py-3 text-right">My Quote</th>
                <th className="px-4 py-3"></th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-100">
              {list.map((r) => (
                <tr key={r.id} className="hover:bg-gray-50">
                  <td className="whitespace-nowrap px-4 py-3 font-medium text-gray-900">
                    {r.unique_id ?? r.parent_enquiry?.unique_id ?? `#${r.id}`}
                  </td>
                  <td className="px-4 py-3 text-gray-700">{r.product?.name ?? "—"}</td>
                  <td className="px-4 py-3 text-gray-700">{r.origin_city ?? "—"}</td>
                  <td className="px-4 py-3 capitalize text-gray-700">
                    {r.status}
                    {r.is_marked && <span className="ml-2 rounded bg-emerald-50 px-2 py-0.5 text-xs text-emerald-700">awarded</span>}
                  </td>
                  <td className="px-4 py-3 text-right text-gray-700">
                    {r.price != null ? `₹ ${r.price}` : "—"}
                  </td>
                  <td className="px-4 py-3 text-right">
                    <Link href={`/transporter/enquiries/${r.id}`} className="text-sm font-medium text-[#CC1414] hover:underline">
                      {r.status === "pending" ? "Respond" : "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>
  );
}
