"use client";

import { useMemo, useState, useEffect } from "react";
import Link from "next/link";
import { useSearchParams, useRouter } from "next/navigation";
import { CATEGORIES } from "@/data/gunbuilderParts";
import type { CategoryId, Part } from "@/types/gunbuilder";
import { CategoryColumn } from "@/components/CategoryColumn";

type GunbuilderProductFromApi = {
  id: number;                 // backend numeric id
  name: string;
  brand: string;
  platform: string;
  partRole: string;
  price: number | null;
  mainImageUrl: string | null;
  buyUrl: string | null;
};

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

// Map backend partRole to your existing CategoryId values.
const PART_ROLE_TO_CATEGORY: Record<string, CategoryId> = {
  "upper-receiver": "upper" as CategoryId,
  barrel: "barrel" as CategoryId,
  handguard: "handguard" as CategoryId,
  "charging-handle": "chargingHandle" as CategoryId,
  "buffer-kit": "buffer" as CategoryId,
  "lower-parts-kit": "lowerParts" as CategoryId,
  sight: "sights" as CategoryId,
  "lower-receiver": "lower" as CategoryId,
  optic: "optic" as CategoryId,
  stock: "stock" as CategoryId,
};

type BuildState = Partial<Record<CategoryId, string>>; // categoryId -> partId

const STORAGE_KEY = "gunbuilder-build-state";

export default function GunbuilderPage() {
  const searchParams = useSearchParams();
  const router = useRouter();
  const [parts, setParts] = useState<Part[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [build, setBuild] = useState<BuildState>(() => {
    if (typeof window !== "undefined") {
      const stored = localStorage.getItem(STORAGE_KEY);
      if (stored) {
        try {
          return JSON.parse(stored);
        } catch {
          return {};
        }
      }
    }
    return {};
  });

  useEffect(() => {
    const controller = new AbortController();

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

        const res = await fetch(
          `${API_BASE_URL}/api/products/gunbuilder?platform=AR-15`,
          { signal: controller.signal },
        );

        if (!res.ok) {
          throw new Error(`Failed to load products (${res.status})`);
        }

        const data: GunbuilderProductFromApi[] = await res.json();

        const normalized: Part[] = data
          .map((p): Part | null => {
            const categoryId = PART_ROLE_TO_CATEGORY[p.partRole];
            if (!categoryId) {
              // Skip any parts we don't know how to map yet
              return null;
            }

            return {
              id: String(p.id), // <<< ALWAYS string
              categoryId,
              name: p.name,
              brand: p.brand,
              price: p.price ?? 0,
              imageUrl: p.mainImageUrl ?? undefined,
              url: p.buyUrl ?? undefined,
              notes: undefined,
            };
          })
          .filter((p): p is Part => p !== null);

        setParts(normalized);
      } catch (err: any) {
        if (err.name === "AbortError") return;
        setError(err.message ?? "Failed to load products");
      } finally {
        setLoading(false);
      }
    }

    fetchProducts();

    return () => controller.abort();
  }, []);

  // Handle URL query parameter for part selection (?select=upper:165)
  useEffect(() => {
    const selectParam = searchParams.get("select");
    if (selectParam) {
      const [categoryId, partId] = selectParam.split(":");
      if (categoryId && partId && CATEGORIES.some((c) => c.id === categoryId)) {
        setBuild((prev) => {
          const updated = {
            ...prev,
            [categoryId as CategoryId]: partId,
          };
          localStorage.setItem(STORAGE_KEY, JSON.stringify(updated));
          return updated;
        });

        router.replace("/gunbuilder", { scroll: false });
      }
    }
  }, [searchParams, router]);

  // Persist build state to localStorage whenever it changes
  useEffect(() => {
    if (typeof window !== "undefined") {
      localStorage.setItem(STORAGE_KEY, JSON.stringify(build));
    }
  }, [build]);

  const partsByCategory: Record<CategoryId, Part[]> = useMemo(() => {
    const grouped = {} as Record<CategoryId, Part[]>;
    for (const category of CATEGORIES) {
      grouped[category.id] = parts.filter(
        (p) => p.categoryId === category.id,
      );
    }
    return grouped;
  }, [parts]);

  const selectedParts: Part[] = useMemo(() => {
    return Object.entries(build)
      .map(([categoryId, partId]) =>
        parts.find((p) => p.id === partId && p.categoryId === categoryId),
      )
      .filter(Boolean) as Part[];
  }, [build, parts]);

  const totalPrice = useMemo(
    () => selectedParts.reduce((sum, p) => sum + p.price, 0),
    [selectedParts],
  );

  const handleSelectPart = (categoryId: CategoryId, partId: string) => {
    setBuild((prev) => ({
      ...prev,
      [categoryId]: partId,
    }));
  };

  return (
    <main className="min-h-screen bg-black text-zinc-50">
      <div className="border-b border-amber-500/20 bg-amber-500/5">
        <div className="mx-auto flex max-w-6xl flex-col gap-1 px-4 py-2 text-[0.75rem] text-amber-100 md:flex-row md:items-center md:justify-between">
          <div className="flex items-center gap-2">
            <span className="rounded-sm bg-amber-500/20 px-2 py-0.5 text-[0.65rem] font-semibold uppercase tracking-[0.18em] text-amber-300">
              Early Access Beta
            </span>
            <span className="hidden text-amber-100/90 md:inline">
              You&apos;re using an early-access prototype of The Armory. Data, pricing, and available parts are still evolving.
            </span>
          </div>
          <span className="text-amber-100/90 md:hidden">
            Early-access prototype. Data and pricing may change.
          </span>
        </div>
      </div>
      <div className="mx-auto max-w-6xl px-4 py-6 lg:py-10">
        {/* Header */}
        <header className="mb-6 flex flex-col gap-2 md:flex-row md:items-end md:justify-between">
          <div>
            <p className="text-xs font-semibold tracking-[0.2em] uppercase text-zinc-500">
              Shadow Standard
            </p>
            <h1 className="mt-1 text-2xl md:text-3xl font-semibold tracking-tight">
              The Armory: <span className="text-amber-300">Early Access</span>
            </h1>
            <p className="mt-2 text-sm text-zinc-400 max-w-xl">
              Explore components from trusted brands, choose one part per category, track live prices, and watch your total build cost update as you go. This early-access builder keeps your setup saved locally so you can come back and refine it anytime.
            </p>
          </div>

          <div className="mt-3 md:mt-0">
            <div className="text-xs text-zinc-400">Current build total</div>
            <div className="text-2xl font-semibold text-amber-300">
              ${totalPrice.toFixed(2)}
            </div>
            <div className="text-xs text-zinc-500">
              {selectedParts.length} / {CATEGORIES.length} categories filled
            </div>
          </div>
        </header>

        {/* Layout */}
        <div className="grid gap-4 lg:grid-cols-[3fr,1.25fr]">
          {/* Categories/parts */}
          <section className="rounded-lg border border-zinc-800 bg-zinc-950/60 p-3 md:p-4">
            {loading && (
              <p className="text-sm text-zinc-500">Loading parts from backend…</p>
            )}
            {error && !loading && (
              <p className="text-sm text-red-400">
                {error} — check that the Ballistic API is running and CORS is
                configured.
              </p>
            )}
            {!loading && !error && (
              <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
                {CATEGORIES.map((category) => (
                  <div
                    key={category.id}
                    className="border border-zinc-800 rounded-md p-2 md:p-3 bg-zinc-950/60"
                  >
                    <CategoryColumn
                      category={category}
                      parts={partsByCategory[category.id]}
                      selectedPartId={build[category.id]}
                      onSelectPart={(partId) =>
                        handleSelectPart(category.id, partId)
                      }
                    />
                  </div>
                ))}
              </div>
            )}
          </section>

          {/* Build Summary */}
          <aside className="rounded-lg border border-zinc-800 bg-zinc-950/80 p-3 md:p-4 flex flex-col">
            <h2 className="text-xs font-semibold tracking-[0.16em] uppercase text-zinc-400 mb-3">
              Current Build
            </h2>

            <div className="flex-1 overflow-y-auto pr-1">
              {selectedParts.length === 0 && (
                <p className="text-sm text-zinc-500">
                  Select a part from each category to start your build.
                </p>
              )}

              <ul className="space-y-2">
                {CATEGORIES.map((cat) => {
                  const selectedPartId = build[cat.id];
                  const part = parts.find(
                    (p) => p.id === selectedPartId && p.categoryId === cat.id,
                  );
                  return (
                    <li key={cat.id}>
                      <div className="text-[0.7rem] uppercase tracking-[0.16em] text-zinc-500">
                        {cat.name}
                      </div>
                      {part ? (
                        <div className="mt-1 flex justify-between items-center gap-2">
                          <div className="text-sm text-zinc-50">
                            <span className="text-zinc-400">
                              {part.brand}{" "}
                            </span>
                            {part.name}
                          </div>
                          <div className="text-xs font-semibold text-amber-300 whitespace-nowrap">
                            ${part.price.toFixed(2)}
                          </div>
                        </div>
                      ) : (
                        <div className="mt-1 text-xs text-zinc-600">
                          Not selected
                        </div>
                      )}
                    </li>
                  );
                })}
              </ul>
            </div>

            {/* CTA */}
            <div className="mt-4 border-t border-zinc-800 pt-3 space-y-2">
              <Link
                href="/gunbuilder/build"
                className={`block w-full rounded-md border border-amber-400/60 bg-amber-400/10 px-3 py-2 text-sm font-medium text-amber-200 hover:bg-amber-400/15 text-center transition-colors ${
                  selectedParts.length === 0
                    ? "opacity-40 cursor-not-allowed pointer-events-none"
                    : ""
                }`}
              >
                Build Summary
              </Link>
              <button
                type="button"
                onClick={() => {
                  setBuild({});
                  localStorage.removeItem(STORAGE_KEY);
                }}
                disabled={selectedParts.length === 0}
                className={`w-full rounded-md border border-zinc-700 bg-zinc-900/50 px-3 py-2 text-sm font-medium text-zinc-300 hover:bg-zinc-800 hover:border-zinc-600 transition-colors ${
                  selectedParts.length === 0
                    ? "opacity-40 cursor-not-allowed"
                    : ""
                }`}
              >
                Clear Build
              </button>
              <p className="mt-2 text-[0.7rem] text-zinc-500">
                View your build breakdown and share it with others.
              </p>
            </div>
          </aside>
        </div>
        <section className="mt-8 rounded-lg border border-zinc-800 bg-zinc-950/80 p-3 md:p-4">
          <h2 className="text-xs font-semibold uppercase tracking-[0.16em] text-amber-300">
            What&apos;s New in Early Access
          </h2>
          <ul className="mt-2 space-y-1 text-sm text-zinc-400">
            <li>• Live parts and pricing pulled from multiple merchants.</li>
            <li>• Category-based layout so you can see at a glance which parts of your build are still missing.</li>
            <li>• Running build total that updates automatically as you add or swap components.</li>
            <li>• Local build persistence so your selections stick around between visits on this device.</li>
          </ul>
        </section>
        <section className="mt-8 rounded-lg border border-zinc-800 bg-zinc-950/80 p-3 md:p-4">
          <h2 className="text-xs font-semibold uppercase tracking-[0.16em] text-amber-300">
            Whats on our roadmap
          </h2>
          <ul className="mt-2 space-y-1 text-sm text-zinc-400">
            <li>• Platform filters (AR-15, AR-9, AR-10)</li>
            <li>• More part categories</li>
            <li>• Richer pricing/stock sync</li>
            <li>• Smarter compatibility checks between components</li>
            <li>• AR9/AR10 support And more</li>
          </ul>
        </section>
      </div>
    </main>
  );
}