import Link from "next/link";
import { Plus } from "lucide-react";
import { sellerApi } from "@/lib/api/seller";
import { requireRole, requireServerToken } from "@/lib/auth/server";
import type { ApiSellerProduct, PaginationMeta } from "@/lib/api/types";
import SafeImage from "@/components/ui/SafeImage";
import { formatValidity, inr } from "./format";

type Tab = "approved" | "requests";

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

const REQUEST_STATUS_STYLES: Record<string, string> = {
  approved: "bg-emerald-50 text-emerald-700 ring-emerald-200",
  pending_review: "bg-amber-50 text-amber-700 ring-amber-200",
  rejected: "bg-red-50 text-red-700 ring-red-200",
  draft: "bg-gray-50 text-gray-600 ring-gray-200",
};

const TABS: { key: Tab; label: string }[] = [
  { key: "approved", label: "Approved" },
  { key: "requests", label: "Requests" },
];

function RequestBadge({ status }: { status: string | null }) {
  const key = status ?? "draft";
  return (
    <span className={`inline-flex rounded-full px-2.5 py-0.5 text-xs font-medium ring-1 ring-inset ${REQUEST_STATUS_STYLES[key] ?? REQUEST_STATUS_STYLES.draft}`}>
      {key.replace("_", " ")}
    </span>
  );
}

/** One label/value line of the card's pricing block. */
function Detail({
  label,
  children,
  strong,
}: {
  label: string;
  children: React.ReactNode;
  strong?: boolean;
}) {
  return (
    <div className="flex items-baseline justify-between gap-3">
      <dt className="shrink-0 text-gray-500">{label}</dt>
      <dd className={`min-w-0 truncate text-right ${strong ? "font-semibold text-gray-900" : "text-gray-700"}`}>
        {children}
      </dd>
    </div>
  );
}

async function loadProducts(token: string, page: number, requestStatus: string, search?: string) {
  try {
    return await sellerApi.products(token, { page, requestStatus, search });
  } catch {
    return { data: [] as ApiSellerProduct[], meta: undefined as PaginationMeta | undefined };
  }
}

/**
 * Server-rendered. Tab, page and search were three pieces of `useState` feeding
 * one effect; as URL params the server can answer the request in full on the
 * first pass, and the search box degrades to a plain GET form that needs no
 * JavaScript at all.
 */
export default async function SellerProductsPage({ searchParams }: PageProps) {
  const token = await requireServerToken("/seller/products");
  await requireRole(["seller"]);

  const sp = await searchParams;
  const page = Math.max(1, Number(sp.page) || 1);
  const search = sp.search?.trim() || "";
  const tab: Tab = sp.tab === "requests" ? "requests" : "approved";

  const requestStatus = tab === "approved" ? "approved" : "pending_review,rejected,draft";
  const { data: list, meta } = await loadProducts(token, page, requestStatus, search || undefined);

  const query = (p: number) => {
    const qs = new URLSearchParams({ tab });
    if (search) qs.set("search", search);
    qs.set("page", String(p));
    return `/seller/products?${qs.toString()}`;
  };

  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">My Products</h1>
        <div className="flex flex-wrap items-center gap-2">
          <Link
            href="/seller/products/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-[#b21010]"
          >
            <Plus className="h-4 w-4" /> Add Product
          </Link>
          {/* Uncontrolled GET form: the browser builds the query string itself. */}
          <form action="/seller/products" method="get" className="flex items-center gap-2">
            <input type="hidden" name="tab" value={tab} />
            <input
              type="text"
              name="search"
              defaultValue={search}
              placeholder="Search products"
              className="rounded-lg border border-gray-200 bg-white px-3 py-2 text-sm focus:border-[#CC1414] focus:outline-none"
            />
            <button type="submit" className="rounded-lg bg-gray-900 px-4 py-2 text-sm font-medium text-white hover:bg-gray-700">
              Search
            </button>
          </form>
        </div>
      </div>

      {/* Tabs: approved (live) vs requests (pending / rejected / draft) */}
      <div className="flex gap-1 border-b border-gray-200">
        {TABS.map((t) => (
          <Link
            key={t.key}
            href={search ? `/seller/products?tab=${t.key}&search=${encodeURIComponent(search)}` : `/seller/products?tab=${t.key}`}
            className={`-mb-px border-b-2 px-4 py-2 text-sm font-medium transition ${
              tab === t.key
                ? "border-[#CC1414] text-[#CC1414]"
                : "border-transparent text-gray-500 hover:text-gray-700"
            }`}
          >
            {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 === "approved" ? "No approved products yet." : "No pending or rejected product requests."}
        </div>
      ) : (
        <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
          {list.map((p) => (
            <div key={p.id} className="overflow-hidden rounded-xl bg-white shadow-sm ring-1 ring-gray-100">
              <div className="relative aspect-video overflow-hidden bg-gray-100">
                <SafeImage
                  src={p.thumbnail || "/logo.png"}
                  alt={p.name}
                  fill
                  sizes="64px"
                  className="object-cover"
                />
              </div>
              <div className="p-4">
                <Link href={`/seller/products/${p.id}`} className="block truncate text-sm font-semibold text-gray-900 hover:text-[#CC1414]">
                  {p.name}
                </Link>
                <p className="mt-1 truncate text-xs text-gray-500">
                  {p.brand?.name ?? "—"}{p.category?.name ? ` · ${p.category.name}` : ""}
                </p>

                {/* What the seller actually has to keep current — visible without
                    opening the product. Ex Price is what buyers compare on, so
                    it is the emphasised figure rather than the base price. */}
                <dl className="mt-3 space-y-1.5 border-t border-gray-100 pt-3 text-xs">
                  <Detail label="Quantity">{p.quantity || "—"}</Detail>
                  <Detail label="Dispatch Within">
                    {p.load_within ? `${p.load_within} days` : "—"}
                  </Detail>
                  <Detail label="Base Price">
                    {p.base_price ? inr.format(p.base_price) : "—"}
                  </Detail>
                  <Detail label="Ex Price" strong>
                    {p.ex_price ? inr.format(p.ex_price) : "—"}
                  </Detail>
                  <Detail label="Price Validity">{formatValidity(p.price_validity)}</Detail>
                </dl>

                <div className="mt-3 flex flex-wrap items-center gap-2">
                  <RequestBadge status={p.request_status} />
                  {tab === "approved" && (
                    <span
                      className={`inline-flex rounded-full px-2.5 py-0.5 text-xs font-medium ring-1 ring-inset ${
                        p.status === "active"
                          ? "bg-emerald-50 text-emerald-700 ring-emerald-200"
                          : "bg-gray-50 text-gray-600 ring-gray-200"
                      }`}
                    >
                      {p.status}
                    </span>
                  )}
                  {tab === "requests" && p.request_status === "rejected" && (
                    <Link href={`/seller/products/${p.id}/edit`} className="text-xs font-medium text-[#CC1414] hover:underline">
                      Edit &amp; resubmit
                    </Link>
                  )}
                </div>
                {/* The product page carries the update rail, so no anchor is needed. */}
                {p.request_status !== "pending_review" && (
                  <Link
                    href={`/seller/products/${p.id}`}
                    className="mt-3 inline-block text-xs font-medium text-[#CC1414] hover:underline"
                  >
                    Update price &amp; stock →
                  </Link>
                )}
              </div>
            </div>
          ))}
        </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>
  );
}
