import Link from "next/link";
import { Plus, FileText } from "lucide-react";
import { customerApi } from "@/lib/api/customer";
import { requireServerToken } from "@/lib/auth/server";
import type { ApiEnquiry, PaginationMeta } from "@/lib/api/types";
import NoData from "@/components/ui/NoData";
import EnquiryStatusFilter from "./EnquiryStatusFilter";
import Countdown from "@/components/rfq/Countdown";
import { formatDateShort } from "@/lib/utils";
import StatusBadge from "@/components/ui/StatusBadge";

const inr = new Intl.NumberFormat("en-IN", {
  style: "currency",
  currency: "INR",
  maximumFractionDigits: 0,
});

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




async function loadEnquiries(token: string, page: number, status?: string) {
  try {
    return await customerApi.enquiries(token, { page, status });
  } catch {
    return { data: [] as ApiEnquiry[], 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
 * list instead of a spinner it has to hydrate before it can even ask.
 *
 * Page and status moved from `useState` into the URL — that is what makes the
 * fetch possible on the server, and it drops the shared `Pagination` component
 * (whose `onPageChange` callback forced the whole page to be a client tree) in
 * favour of plain links.
 */
export default async function EnquiriesPage({ searchParams }: PageProps) {
  const token = await requireServerToken("/rfq");
  const sp = await searchParams;

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

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

  const query = (p: number) =>
    status ? `/rfq?status=${encodeURIComponent(status)}&page=${p}` : `/rfq?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="flex items-center gap-2 text-2xl font-bold text-gray-900">
          <FileText className="h-6 w-6 text-[#CC1414]" /> My Requirements
        </h1>
        <div className="flex items-center gap-2">
          <EnquiryStatusFilter value={status} />
          <Link
            href="/rfq/new"
            className="inline-flex items-center gap-1.5 rounded-lg bg-[#CC1414] px-4 py-2 text-sm font-medium text-white hover:bg-[#a30f0f]"
          >
            <Plus className="h-4 w-4" /> Post Requirement
          </Link>
        </div>
      </div>

      {list.length === 0 ? (
        <NoData
          title="No enquiries yet"
          message="Submit your first RFQ to receive quotations from verified suppliers."
          action={
            <Link
              href="/rfq/new"
              className="inline-block rounded-lg bg-[#CC1414] px-4 py-2 text-sm font-medium text-white hover:bg-[#a30f0f]"
            >
              Find Best Rate
            </Link>
          }
        />
      ) : (
        <div className="grid grid-cols-1 gap-3">
          {list.map((e) => (
            <Link
              key={e.id}
              href={`/rfq/${e.id}`}
              className="flex items-center justify-between rounded-xl bg-white p-5 shadow-sm ring-1 ring-gray-100 transition hover:ring-[#CC1414]/30"
            >
              <div className="min-w-0">
                <div className="flex flex-wrap items-center gap-2">
                  <div className="font-semibold text-gray-900">
                    {[e.product?.name, e.size_label].filter(Boolean).join(" ") || "—"}
                  </div>
                  {e.bidding?.is_live ? (
                    <span className="inline-flex items-center gap-1.5 rounded-full bg-red-50 px-2 py-0.5 text-[11px] font-semibold text-[#CC1414] ring-1 ring-red-200">
                      <span className="h-1.5 w-1.5 animate-pulse rounded-full bg-[#CC1414]" /> LIVE
                    </span>
                  ) : null}
                  <StatusBadge kind="rfq" code={e.status_code} label={e.status_label ?? e.status} />
                </div>
                <div className="mt-1 text-xs text-gray-500">
                  {e.unique_id}
                  {e.quantity ? ` · ${e.quantity} ${e.unit_label ?? ""}`.trimEnd() : ""}
                  {e.delivery_city ? ` · to ${e.delivery_city}` : ""}
                  {e.brand?.name ? ` · ${e.brand.name}` : ""}
                </div>
              </div>
              <div className="text-right text-xs text-gray-500">
                {/* Best price first: it is the only number the buyer came for. */}
                {e.bidding?.best_for_price != null && (
                  <div className="text-sm font-semibold text-emerald-700">
                    {inr.format(e.bidding.best_for_price)}
                    {e.unit_label ? <span className="font-normal"> / {e.unit_label}</span> : null}
                  </div>
                )}
                {e.bidding?.is_live && (
                  <div className="font-medium text-[#CC1414]">
                    <Countdown endsAt={e.bidding.ends_at} fallbackSeconds={e.bidding.seconds_left} />
                  </div>
                )}
                {e.is_marked_by_seller && <div className="text-emerald-600">Quote selected</div>}
                {e.order_id && <div className="text-blue-600">Order: {e.order_id}</div>}
                {e.created_at && <div>{formatDateShort(e.created_at)}</div>}
              </div>
            </Link>
          ))}
        </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>
  );
}
