import Link from "next/link";
import { notFound } from "next/navigation";

const API_BASE_URL =
  process.env.NEXT_PUBLIC_API_BASE_URL ?? "http://localhost:8080";

export default async function BuildBreakdownPage({
  params,
}: {
  params: { buildId: string };
}) {
  // You may need to add/confirm this endpoint in backend:
  // GET /api/v1/builds/{uuid}
  const res = await fetch(`${API_BASE_URL}/api/v1/builds/${params.buildId}`, {
    cache: "no-store",
  });

  if (res.status === 404) return notFound();

  const build = await res.json().catch(() => null);
  if (!build) return notFound();

  return (
    <main className="mx-auto max-w-6xl px-4 py-10">
      <Link href="/builds" className="text-sm text-zinc-400 hover:text-zinc-200">
        ← Back to Community Builds
      </Link>

      <div className="mt-6 rounded-lg border border-zinc-900 bg-zinc-950/60 p-6">
        <h1 className="text-2xl font-semibold text-zinc-50">
          {build.title ?? "Untitled build"}
        </h1>

        {build.description && (
          <p className="mt-2 text-sm text-zinc-400">{build.description}</p>
        )}

        <div className="mt-6">
          <h2 className="text-sm font-semibold text-zinc-200">Parts</h2>

          {/* Adjust keys to match your API payload */}
          <div className="mt-3 space-y-2">
            {(build.items ?? build.buildItems ?? []).map((it: any) => (
              <div
                key={it.uuid ?? it.id}
                className="flex items-center justify-between rounded-md border border-zinc-900 bg-black/30 px-3 py-2"
              >
                <div>
                  <div className="text-sm text-zinc-100">
                    {it.product?.name ?? it.name ?? "Part"}
                  </div>
                  <div className="text-xs text-zinc-500">
                    {it.slot ?? it.partRole ?? "—"}
                  </div>
                </div>
                <div className="text-xs text-zinc-400">
                  x{it.quantity ?? 1}
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </main>
  );
}