"use client";

import { useEffect, useMemo, useState } from "react";
import Link from "next/link";
import PlatformSwitcher from "./PlatformSwitcher";
import Image from "next/image";

const API_BASE_URL = process.env.NEXT_PUBLIC_API_BASE_URL ?? "";

type ProductListDto = {
  id: string;          // your API returns strings sometimes; keep it flexible
  name: string;
  brand: string;
  platform: string;
  partRole: string;
  categoryKey: string | null;
  price: number | null;
  buyUrl: string | null;
  imageUrl: string | null;
};

function safeSlugify(input: string) {
  return (input ?? "")
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, "-")
    .replace(/(^-|-$)/g, "")
    .slice(0, 80);
}

export default function PartsListPageClient(props: {
  platform: string;
  partRole: string;
}) {
  const { platform, partRole } = props;

  const [items, setItems] = useState<ProductListDto[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // Simple client-side search (fast + good enough for now)
  const [q, setQ] = useState("");

  useEffect(() => {
    let cancelled = false;

    async function load() {
      try {
        setLoading(true);
        setError(null);

        // Your current list endpoint:
        // GET /api/v1/products?platform=AR-15&partRoles=upper-receiver
        const url = `/api/catalog/products?platform=${encodeURIComponent(platform)}&partRoles=${encodeURIComponent(partRole)}`;

        const res = await fetch(url, {
          headers: { Accept: "application/json" },
          credentials: 'include',
        });
        if (!res.ok) {
          const txt = await res.text().catch(() => "");
          throw new Error(`Failed to load products (${res.status}): ${txt}`);
        }

        const data: ProductListDto[] = await res.json();
        if (!cancelled) setItems(data);
      } catch (e: any) {
        if (!cancelled) setError(e?.message ?? "Failed to load products");
      } finally {
        if (!cancelled) setLoading(false);
      }
    }

    load();
    return () => { cancelled = true; };
  }, [platform, partRole]);

  const filtered = useMemo(() => {
    const needle = q.trim().toLowerCase();
    if (!needle) return items;

    return items.filter((p) => {
      const blob = `${p.brand ?? ""} ${p.name ?? ""} ${p.categoryKey ?? ""}`.toLowerCase();
      return blob.includes(needle);
    });
  }, [items, q]);

  return (
    <main className="min-h-screen bg-black text-zinc-50">
      <div className="mx-auto max-w-6xl px-4 py-6 lg:py-10">
        <header className="mb-6 flex flex-col gap-3">
          <div className="flex items-center justify-between gap-4">
            <div>
              <p className="text-xs font-semibold tracking-[0.2em] uppercase text-zinc-500">
                Battl Builders
              </p>
              <h1 className="mt-1 text-2xl md:text-3xl font-semibold tracking-tight">
                Parts: <span className="text-amber-300">{partRole}</span>
              </h1>
            </div>

            <PlatformSwitcher currentPlatform={platform} partRole={partRole} />
          </div>

          <div className="flex items-center gap-3">
            <input
              value={q}
              onChange={(e) => setQ(e.target.value)}
              placeholder="Search brand, name, category…"
              className="w-full rounded-md border border-zinc-700 bg-zinc-950/80 px-3 py-2 text-sm text-zinc-100 outline-none focus:border-amber-400"
            />
          </div>
        </header>

        {loading && <p className="text-sm text-zinc-500">Loading parts…</p>}
        {error && (
          <div className="rounded-md border border-red-500/40 bg-red-500/10 px-3 py-2 text-sm text-red-200">
            {error}
          </div>
        )}

        {!loading && !error && (
          <section className="rounded-lg border border-zinc-800 bg-zinc-950/70 p-3 md:p-4">
            <div className="mb-2 flex items-center justify-between">
              <p className="text-xs uppercase tracking-[0.14em] text-zinc-500">
                Results
              </p>
              <p className="text-xs text-zinc-400">
                {filtered.length} items
              </p>
            </div>

            <div className="grid grid-cols-1 gap-3 md:grid-cols-2">
              {filtered.map((p) => {
                const id = String(p.id);
                const slug = safeSlugify(p.name);
                const href = `/parts/${encodeURIComponent(platform)}/${encodeURIComponent(partRole)}/${id}-${slug}`;

                return (
                  <Link
                    key={`${p.id}`}
                    href={href}
                    className="group rounded-lg border border-zinc-800 bg-black/30 p-3 hover:border-zinc-700"
                  >
                    <div className="flex gap-3">
                      <div className="relative h-16 w-16 overflow-hidden rounded-md border border-zinc-800 bg-zinc-950">
                        {/* eslint-disable-next-line @next/next/no-img-element */}
                        {p.imageUrl ? (
                          <Image
                            src={p.imageUrl}
                            alt={p.name}
                            fill
                            sizes="64px"
                            className="object-cover"
                          />
                        ) : (
                          <div className="h-full w-full grid place-items-center text-xs text-zinc-600">
                            —
                          </div>
                        )}
                      </div>

                      <div className="flex-1">
                        <p className="text-xs uppercase tracking-[0.14em] text-zinc-500">
                          {p.brand}
                        </p>
                        <p className="mt-1 text-sm font-medium text-zinc-100 group-hover:text-amber-200">
                          {p.name}
                        </p>
                        <div className="mt-2 flex items-center justify-between">
                          <p className="text-xs text-zinc-500 line-clamp-1">
                            {p.categoryKey ?? "—"}
                          </p>
                          <p className="text-xs font-semibold text-zinc-200">
                            {typeof p.price === "number" ? `$${p.price.toFixed(2)}` : "—"}
                          </p>
                        </div>
                      </div>
                    </div>
                  </Link>
                );
              })}
            </div>
          </section>
        )}
      </div>
    </main>
  );
}
