import Link from "next/link";
import { sellerApi } from "@/lib/api/seller";
import { requireRole, requireServerToken } from "@/lib/auth/server";
import type { ApiSellerOrder, PaginationMeta } from "@/lib/api/types";
import SellerOrderStatusFilter from "./SellerOrderStatusFilter";
import StatusBadge from "@/components/ui/StatusBadge";

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

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


async function loadOrders(token: string, page: number, status?: string) {
  try {
    return await sellerApi.orders(token, { page, status });
  } catch {
    return { data: [] as ApiSellerOrder[], meta: undefined as PaginationMeta | undefined };
  }
}

/**
 * Server-rendered: the token comes from the cookie during SSR, so the browser
 * receives a populated table instead of a spinner that only starts fetching
 * once the bundle has hydrated.
 *
 * `RequireRole` is gone because it did its check client-side, after the page had
 * already been sent. The cached user cookie gives the same answer on the server;
 * the API remains the real authority on what a seller may read.
 */
export default async function SellerOrdersPage({ searchParams }: PageProps) {
  const token = await requireServerToken("/seller/orders");
  await requireRole(["seller"]);

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

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

  const query = (p: number) =>
    status ? `/seller/orders?status=${status}&page=${p}` : `/seller/orders?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="text-2xl font-bold text-gray-900">Orders</h1>
        <SellerOrderStatusFilter value={status} />
      </div>

      {orders.length === 0 ? (
        <div className="rounded-xl bg-white p-10 text-center text-gray-500 shadow-sm ring-1 ring-gray-100">No orders found.</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">Order ID</th>
                <th className="px-4 py-3">Product</th>
                <th className="px-4 py-3">Customer</th>
                <th className="px-4 py-3">Status</th>
                <th className="px-4 py-3 text-right">Amount</th>
                <th className="px-4 py-3"></th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-100">
              {orders.map((o) => (
                <tr key={o.id} className="hover:bg-gray-50">
                  <td className="whitespace-nowrap px-4 py-3 font-medium text-gray-900">{o.order_id ?? o.unique_id}</td>
                  <td className="px-4 py-3 text-gray-700">{o.product?.name ?? "—"}</td>
                  <td className="px-4 py-3 text-gray-700">{o.customer?.name ?? "—"}</td>
                  <td className="px-4 py-3">
                    <StatusBadge kind="order" code={o.status_code} label={o.status_label ?? o.status} />
                  </td>
                  <td className="px-4 py-3 text-right font-semibold text-gray-900">{inr.format(o.final_amount || o.total_amount)}</td>
                  <td className="px-4 py-3 text-right">
                    <Link href={`/seller/orders/${o.id}`} className="text-sm font-medium text-[#CC1414] hover:underline">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>
  );
}
