import Link from "next/link";
import { Package, Search } from "lucide-react";
import { sellerApi } from "@/lib/api/seller";
import { ApiException } from "@/lib/api/client";
import { requireRole, requireServerToken } from "@/lib/auth/server";
import type { ApiSellerCommodityProduct, PaginationMeta } from "@/lib/api/types";
import NoData from "@/components/ui/NoData";
import SafeImage from "@/components/ui/SafeImage";
import CommodityStatusFilter from "./CommodityStatusFilter";

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

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

async function loadCommodityProducts(
  token: string,
  page: number,
  search?: string,
  status?: string
) {
  try {
    const r = await sellerApi.commodityProducts(token, { page, perPage: 15, search, status });
    return { items: r.data, meta: r.meta, err: null as string | null };
  } catch (e) {
    return {
      items: [] as ApiSellerCommodityProduct[],
      meta: undefined as PaginationMeta | undefined,
      err: e instanceof ApiException ? e.message : "Failed to load.",
    };
  }
}

/**
 * Server-rendered. Search, status and page moved from `useState` into the URL,
 * which is what lets the fetch happen during SSR instead of after hydration —
 * and it makes a filtered view linkable, which the old version could not do.
 */
export default async function SellerCommodityProductsPage({ searchParams }: PageProps) {
  const token = await requireServerToken("/seller/commodity-products");
  await requireRole(["seller"]);

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

  const { items, meta, err } = await loadCommodityProducts(
    token,
    page,
    search || undefined,
    statusFilter || undefined
  );

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

  return (
    <div className="space-y-4">
      <div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
        <h1 className="flex items-center gap-2 text-2xl font-bold text-gray-900">
          <Package className="h-6 w-6 text-[#CC1414]" /> My Commodity Products
        </h1>
      </div>

      <div className="flex flex-col gap-2 rounded-xl bg-white p-3 shadow-sm ring-1 ring-gray-100 sm:flex-row">
        {/* Uncontrolled GET form: the browser builds the query string itself. */}
        <form action="/seller/commodity-products" method="get" className="flex flex-1 items-center gap-2">
          {statusFilter && <input type="hidden" name="status" value={statusFilter} />}
          <div className="relative flex-1">
            <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400" />
            <input
              type="text"
              name="search"
              defaultValue={search}
              placeholder="Search by name…"
              className="w-full rounded-lg border border-gray-200 bg-white py-2 pl-9 pr-3 text-sm focus:border-[#CC1414] focus:outline-none focus:ring-1 focus:ring-[#CC1414]"
            />
          </div>
          <button
            type="submit"
            className="rounded-lg bg-[#CC1414] px-4 py-2 text-sm font-medium text-white hover:bg-[#a30f0f]"
          >
            Search
          </button>
        </form>
        <CommodityStatusFilter value={statusFilter} search={search} />
      </div>

      {err && <div className="rounded-xl bg-red-50 p-4 text-sm text-red-700 ring-1 ring-red-200">{err}</div>}

      {items.length === 0 ? (
        <NoData title="No commodity products" message="No commodity products configured yet." />
      ) : (
        <div className="overflow-x-auto rounded-xl bg-white shadow-sm ring-1 ring-gray-100">
          <div className="overflow-x-auto">
            <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">Product</th>
                  <th className="px-4 py-3">Brand</th>
                  <th className="px-4 py-3">Category</th>
                  <th className="px-4 py-3">Region</th>
                  <th className="px-4 py-3 text-right">Base Price</th>
                  <th className="px-4 py-3">GST</th>
                  <th className="px-4 py-3">Status</th>
                  <th className="px-4 py-3"></th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-100">
                {items.map((it) => {
                  const thumb = it.thumbnail || it.product?.thumbnail;
                  return (
                    <tr key={it.id} className="hover:bg-gray-50">
                      <td className="px-4 py-3">
                        <div className="flex items-center gap-3">
                          <div className="relative h-10 w-10 overflow-hidden rounded-md ring-1 ring-gray-100">
                            <SafeImage
                              src={thumb || "/logo.png"}
                              alt={it.name ?? it.product?.name ?? "Product"}
                              fill
                              sizes="40px"
                              className="object-cover"
                            />
                          </div>
                          <div>
                            <div className="font-medium text-gray-900">{it.name ?? it.product?.name ?? "—"}</div>
                            <div className="text-xs text-gray-500">{it.unit?.name ?? ""}</div>
                          </div>
                        </div>
                      </td>
                      <td className="px-4 py-3 text-gray-700">{it.brand?.name ?? "—"}</td>
                      <td className="px-4 py-3 text-gray-700">{it.category?.name ?? "—"}</td>
                      <td className="px-4 py-3 text-gray-700">
                        {[it.city, it.state].filter(Boolean).join(", ") || "—"}
                      </td>
                      <td className="px-4 py-3 text-right font-semibold text-gray-900">{inr.format(it.base_price)}</td>
                      <td className="px-4 py-3 text-gray-700">{it.gst}%</td>
                      <td className="px-4 py-3">
                        <span
                          className={`rounded-full px-2 py-0.5 text-xs font-medium ${
                            it.status === "active"
                              ? "bg-emerald-100 text-emerald-700"
                              : "bg-gray-200 text-gray-600"
                          }`}
                        >
                          {it.status ?? "—"}
                        </span>
                      </td>
                      <td className="px-4 py-3 text-right">
                        <Link
                          href={`/seller/commodity-products/${it.id}`}
                          className="rounded-md bg-gray-100 px-3 py-1 text-xs font-medium text-gray-800 hover:bg-gray-200"
                        >
                          View
                        </Link>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>

          {meta && meta.last_page > 1 && (
            <div className="flex items-center justify-between border-t border-gray-100 px-4 py-3 text-sm">
              <span className="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">
                {meta.current_page > 1 ? (
                  <Link href={query(page - 1)} className="rounded-md bg-gray-100 px-3 py-1 hover:bg-gray-200">
                    Prev
                  </Link>
                ) : (
                  <span className="rounded-md bg-gray-100 px-3 py-1 opacity-50">Prev</span>
                )}
                {meta.current_page < meta.last_page ? (
                  <Link href={query(page + 1)} className="rounded-md bg-gray-100 px-3 py-1 hover:bg-gray-200">
                    Next
                  </Link>
                ) : (
                  <span className="rounded-md bg-gray-100 px-3 py-1 opacity-50">Next</span>
                )}
              </div>
            </div>
          )}
        </div>
      )}
    </div>
  );
}
