"use client";

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

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 [build, setBuild] = useState<BuildState>(() => {
    // Initialize from localStorage if available
    if (typeof window !== "undefined") {
      const stored = localStorage.getItem(STORAGE_KEY);
      if (stored) {
        try {
          return JSON.parse(stored);
        } catch {
          return {};
        }
      }
    }
    return {};
  });

  // Handle URL query parameter for part selection
  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]: partId,
          };
          // Persist to localStorage
          localStorage.setItem(STORAGE_KEY, JSON.stringify(updated));
          return updated;
        });
        // Remove query param from URL
        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;
  }, []);

  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]);

  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="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">
              Gunbuilder <span className="text-amber-300">Prototype</span>
            </h1>
            <p className="mt-2 text-sm text-zinc-400 max-w-xl">
              Choose one part per category to assemble an AR-15 build. Prices
              and links are mock data for now—but the flow is close to what
              the real tool will be.
            </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">
            <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">
              <button
                type="button"
                className="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 disabled:opacity-40 disabled:cursor-not-allowed"
                disabled={selectedParts.length === 0}
                onClick={() => {
                  console.log("Build:", build);
                  alert(
                    "Prototype only: in the real app this would go to a sharable build summary with affiliate links.",
                  );
                }}
              >
                Continue to Buy (Prototype)
              </button>
              <p className="mt-2 text-[0.7rem] text-zinc-500">
                In the production version, this will take you to a build page with
                retailer links and sharing options.
              </p>
            </div>
          </aside>
        </div>
      </div>
    </main>
  );
}
