import Link from "next/link";
import { Bookmark } from "lucide-react";
import { customerApi } from "@/lib/api/customer";
import { requireServerToken } from "@/lib/auth/server";
import type { ApiWatchlistItem, PaginationMeta } from "@/lib/api/types";
import NoData from "@/components/ui/NoData";
import SafeImage from "@/components/ui/SafeImage";
import { removeFromWatchlist } from "./actions";
import RemoveButton from "./RemoveButton";
import { formatCurrency, formatUnit } from "@/lib/utils";

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

async function loadWatchlist(token: string, page: number) {
  try {
    return await customerApi.watchlist(token, { page, perPage: 12 });
  } catch {
    return { data: [] as ApiWatchlistItem[], meta: undefined as PaginationMeta | undefined };
  }
}

/**
 * Server-rendered list with a Server Action for removal — no `useEffect` fetch,
 * no `useState` copy of the list, and no client-side auth gate. The token is
 * read from the cookie during SSR, so the first response already contains the
 * user's saved products.
 */
export default async function WatchlistPage({ searchParams }: PageProps) {
  const token = await requireServerToken("/watchlist");
  const sp = await searchParams;
  const page = Math.max(1, Number(sp.page) || 1);

  const { data: items, meta } = await loadWatchlist(token, page);

  return (
    <div className="space-y-4">
      <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
        <h1 className="flex items-center gap-2 text-2xl font-bold text-gray-900">
          <Bookmark className="h-6 w-6 text-[#CC1414]" /> Watchlist
        </h1>
        <Link
          href="/products"
          className="rounded-lg bg-[#CC1414] px-4 py-2 text-sm font-medium text-white hover:bg-[#a30f0f]"
        >
          Browse Products
        </Link>
      </div>

      {items.length === 0 ? (
        <NoData
          title="Your watchlist is empty"
          message="Bookmark products from the catalog to keep track of them here."
          action={
            <Link
              href="/products"
              className="inline-block rounded-lg bg-[#CC1414] px-4 py-2 text-sm font-medium text-white hover:bg-[#a30f0f]"
            >
              Browse Products
            </Link>
          }
        />
      ) : (
        <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
          {items.map((it) => {
            const p = it.product;
            const sp = it.seller_product;
            return (
              <div
                key={it.id}
                className="overflow-hidden rounded-xl bg-white shadow-sm ring-1 ring-gray-100 transition hover:shadow-md"
              >
                <div className="relative aspect-[4/3] bg-gray-50">
                  <SafeImage
                    src={p?.thumbnail || "/logo.png"}
                    alt={p?.name ?? "Product"}
                    fill
                    sizes="(max-width: 640px) 100vw, 33vw"
                    className="object-cover"
                  />
                </div>
                <div className="p-4">
                  <div className="text-xs text-gray-500">{p?.category?.name ?? "—"}</div>
                  <Link
                    href={p?.slug ? `/products/${p.slug}` : "#"}
                    className="mt-1 line-clamp-1 block text-sm font-semibold text-gray-900 hover:text-[#CC1414]"
                  >
                    {p?.name ?? "Product"}
                  </Link>
                  <div className="mt-2 flex items-center justify-between">
                    <div className="text-sm text-gray-700">
                      {sp?.brand?.name && <span className="text-xs text-gray-500">{sp.brand.name}</span>}
                      {sp?.price && (
                        <div className="font-semibold text-gray-900">
                          {formatCurrency(Number(sp.price))}
                          {p?.unit?.name && <span className="text-xs text-gray-500"> / {formatUnit(p.unit.name)}</span>}
                        </div>
                      )}
                    </div>
                    <form action={removeFromWatchlist}>
                      <input type="hidden" name="id" value={it.id} />
                      <RemoveButton />
                    </form>
                  </div>
                </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>
          <div className="flex gap-2">
            {page > 1 ? (
              <Link href={`/watchlist?page=${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={`/watchlist?page=${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>
  );
}
