import Link from "next/link";
import { customerApi } from "@/lib/api/customer";
import { requireServerToken } from "@/lib/auth/server";
import type { ApiOrder, PaginationMeta } from "@/lib/api/types";
import OrderStatusFilter from "./OrderStatusFilter";
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 customerApi.orders(token, { page, status });
  } catch {
    return { data: [] as ApiOrder[], meta: undefined as PaginationMeta | undefined };
  }
}

/**
 * Server-rendered: the token comes from the cookie via `requireServerToken`, so
 * the orders are fetched during SSR and the browser receives a populated table.
 *
 * The previous client version gated its fetch on `useToken`, which reads the
 * same cookie inside an effect — so nothing was requested until the bundle had
 * downloaded and hydrated. Filter and page live in the URL now instead of
 * `useState`, which is what lets the server do the fetching at all.
 */
export default async function OrdersPage({ searchParams }: PageProps) {
  const token = await requireServerToken("/orders");
  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 ? `/orders?status=${status}&page=${p}` : `/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>
        <OrderStatusFilter 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">Brand</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.brand?.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={`/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>
  );
}
