import Link from "next/link";
import { sellerApi } from "@/lib/api/seller";
import { requireRole, requireServerToken } from "@/lib/auth/server";
import type { ApiSellerQuotation, PaginationMeta } from "@/lib/api/types";
import Countdown from "@/components/rfq/Countdown";
import PriceOptionBadge from "@/components/rfq/PriceOptionBadge";
import StatusBadge from "@/components/ui/StatusBadge";

type Tab = "received" | "replied" | "closed";

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

const TABS: { key: Tab; label: string }[] = [
  { key: "received", label: "New RFQs" },
  { key: "replied", label: "My Bids" },
  { key: "closed", label: "Closed" },
];

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

async function loadRfqs(token: string, page: number, tab: Tab) {
  try {
    return await sellerApi.rfqs(token, { page, tab });
  } catch {
    return { data: [] as ApiSellerQuotation[], meta: undefined as PaginationMeta | undefined };
  }
}

/**
 * The seller's RFQ inbox.
 *
 * Server-rendered: the tab is a URL param rather than `useState`, so the right
 * query is resolved before the first byte is sent and the tab is shareable and
 * back-button friendly. Only the per-row countdowns hydrate.
 *
 * Rows are ordered live-first, closing-soonest by the API — a seller's
 * attention is worth the most on the auction about to expire.
 */
export default async function SellerQuotationsPage({ searchParams }: PageProps) {
  const token = await requireServerToken("/seller/quotations");
  await requireRole(["seller"]);

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

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

  const query = (p: number) => `/seller/quotations?tab=${tab}&page=${p}`;

  return (
    <div className="space-y-4">
      <div>
        <h1 className="text-2xl font-bold text-gray-900">RFQs</h1>
        <p className="text-sm text-gray-600">
          Live auctions you have been invited to. Enter your basic price — the gauge difference,
          your charges and GST give the Ex price of each size.
        </p>
      </div>

      <div className="inline-flex rounded-lg bg-white p-1 shadow-sm ring-1 ring-gray-100">
        {TABS.map((t) => (
          <Link
            key={t.key}
            href={`/seller/quotations?tab=${t.key}`}
            className={`rounded-md px-4 py-2 text-sm font-medium ${
              tab === t.key ? "bg-[#CC1414] text-white" : "text-gray-700 hover:bg-gray-50"
            }`}
          >
            {t.label}
          </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 === "received"
            ? "No new RFQs awaiting your rate. You'll be notified the moment one arrives."
            : "You have not bid on any RFQ yet."}
        </div>
      ) : (
        <div className="grid grid-cols-1 gap-3">
          {list.map((r) => {
            const live = r.bidding?.is_live ?? false;

            return (
              <Link
                key={r.id}
                href={`/seller/quotations/${r.id}`}
                className="rounded-xl bg-white p-5 shadow-sm ring-1 ring-gray-100 transition hover:ring-[#CC1414]/30"
              >
                <div className="flex flex-wrap items-start justify-between gap-3">
                  <div className="min-w-0">
                    <div className="flex flex-wrap items-center gap-2">
                      <span className="font-semibold text-gray-900">
                        {[r.product?.name, r.size_label].filter(Boolean).join(" ") || "—"}
                      </span>
                      {live ? (
                        <span className="inline-flex items-center gap-1.5 rounded-full bg-amber-50 px-2 py-0.5 text-[11px] font-semibold text-amber-800 ring-1 ring-amber-200">
                          <span className="h-1.5 w-1.5 animate-pulse rounded-full bg-amber-600" /> LIVE
                        </span>
                      ) : (
                        <span className="rounded-full bg-gray-100 px-2 py-0.5 text-[11px] font-semibold text-gray-600">
                          Closed
                        </span>
                      )}
                      {/* One status per row: new / rate submitted / won / not selected (B39). */}
                      <StatusBadge kind="rfq" code={r.status_code} label={r.status_label} className="text-[11px]" />
                      <PriceOptionBadge value={r.price_option} />
                    </div>
                    <p className="mt-1 text-xs text-gray-500">
                      {r.unique_id}
                      {r.quantity ? ` · ${r.quantity} ${r.unit_label ?? ""}`.trimEnd() : ""}
                      {r.delivery_city ? ` · to ${r.delivery_city}` : ""}
                      {r.brand?.name ? ` · ${r.brand.name}` : ""}
                    </p>
                  </div>

                  <div className="text-right">
                    {live && (
                      <div className="text-sm font-semibold text-[#CC1414]">
                        <Countdown
                          endsAt={r.bidding.ends_at}
                          fallbackSeconds={r.bidding.seconds_left}
                        />
                      </div>
                    )}
                    {r.my_reply?.for_price != null || Number(r.my_reply?.base_price ?? 0) > 0 ? (
                      <div className="text-xs text-gray-500">
                        Your {r.my_reply?.for_price != null ? "F.O.R" : "rate"}{" "}
                        <span className="font-semibold text-gray-900">
                          {inr.format(Number(r.my_reply?.for_price ?? r.my_reply?.base_price ?? 0))}
                        </span>
                      </div>
                    ) : live ? (
                      <div className="text-xs font-medium text-[#CC1414]">Submit your rate</div>
                    ) : null}
                  </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>
  );
}
