"use client";

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

type ViewMode = "card" | "list";

type GunbuilderProductFromApi = {
  id: string;
  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";

const CATEGORY_TO_PART_ROLES: Record<CategoryId, string[]> = {
  upper: ["upper-receiver"],
  barrel: ["barrel"],
  handguard: ["handguard"],
  chargingHandle: ["charging-handle"],
  buffer: ["buffer-kit"],
  lowerParts: ["lower-parts-kit"],
  sights: ["sight"],
};

// sort options
type SortOption = "relevance" | "price-asc" | "price-desc" | "brand-asc";

// build state type + storage key (matches /gunbuilder)
type BuildState = Partial<Record<CategoryId, string>>;
const STORAGE_KEY = "gunbuilder-build-state";

export default function CategoryPage() {
  const params = useParams();
  const categoryId = params.categoryId as CategoryId;
  const router = useRouter();

  const [viewMode, setViewMode] = useState<ViewMode>("list");
  const [parts, setParts] = useState<Part[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // filter + sort state
  const [brandFilter, setBrandFilter] = useState<string>("all");
  const [sortBy, setSortBy] = useState<SortOption>("relevance");
  const [searchQuery, setSearchQuery] = useState<string>("");

  //  build state for this page, synced with localStorage
  const [build, setBuild] = useState<BuildState>(() => {
    if (typeof window === "undefined") return {};
    try {
      const stored = window.localStorage.getItem(STORAGE_KEY);
      return stored ? (JSON.parse(stored) as BuildState) : {};
    } catch {
      return {};
    }
  });

  const category = useMemo(
    () => CATEGORIES.find((c) => c.id === categoryId),
    [categoryId],
  );

  useEffect(() => {
    if (!categoryId) return;

    const controller = new AbortController();

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

        const roles = CATEGORY_TO_PART_ROLES[categoryId] ?? [];

        const search = new URLSearchParams();
        search.set("platform", "AR-15");
        roles.forEach((r) => search.append("partRoles", r));

        const url = `${API_BASE_URL}/api/products/gunbuilder${
          roles.length ? `?${search.toString()}` : ""
        }`;

        const res = await fetch(url, { 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) => ({
          id: p.id,
          categoryId,
          name: p.name,
          brand: p.brand,
          price: p.price ?? 0,
          imageUrl: p.mainImageUrl ?? undefined,
          url: p.buyUrl ?? undefined,
          notes: undefined,
        }));

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

    fetchCategoryParts();

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

  //  persist build to localStorage whenever it changes
  useEffect(() => {
    if (typeof window === "undefined") return;
    try {
      window.localStorage.setItem(STORAGE_KEY, JSON.stringify(build));
    } catch {
      // ignore
    }
  }, [build]);

  //  handler to toggle Add / Remove for this category
  const handleTogglePart = (categoryId: CategoryId, partId: string) => {
    const isSelected = build[categoryId] === partId;

    if (isSelected) {
      // Remove from build
      setBuild((prev) => {
        const updated: BuildState = { ...prev };
        delete updated[categoryId];
        return updated;
      });
    } else {
      // Add to build and navigate back to main gunbuilder page
      setBuild((prev) => ({
        ...prev,
        [categoryId]: partId,
      }));
      router.push("/gunbuilder");
    }
  };

  // available brands for filter
  const availableBrands = useMemo(
    () =>
      Array.from(new Set(parts.map((p) => p.brand)))
        .filter(Boolean)
        .sort((a, b) => a.localeCompare(b)),
    [parts],
  );

  // filtered + sorted parts with selected part pinned to top
  const filteredParts = useMemo(() => {
    let result = [...parts];

    if (brandFilter !== "all") {
      result = result.filter((p) => p.brand === brandFilter);
    }

    const normalizedQuery = searchQuery.trim().toLowerCase();
    if (normalizedQuery) {
      result = result.filter((p) => {
        const name = p.name.toLowerCase();
        const brand = p.brand.toLowerCase();
        return (
          name.includes(normalizedQuery) ||
          brand.includes(normalizedQuery)
        );
      });
    }

    switch (sortBy) {
      case "price-asc":
        result.sort((a, b) => a.price - b.price);
        break;
      case "price-desc":
        result.sort((a, b) => b.price - a.price);
        break;
      case "brand-asc":
        result.sort((a, b) => a.brand.localeCompare(b.brand));
        break;
      case "relevance":
      default:
        // leave in backend order
        break;
    }

    // Pin the currently selected part (for this category) to the top, if any
    const selectedId = build[categoryId];
    if (selectedId) {
      const selected = result.filter((p) => p.id === selectedId);
      const others = result.filter((p) => p.id !== selectedId);
      result = [...selected, ...others];
    }

    return result;
  }, [parts, brandFilter, sortBy, build, categoryId, searchQuery]);

  if (!category) {
    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">
          <div className="text-center">
            <h1 className="text-2xl font-semibold text-zinc-50 mb-4">
              Category Not Found
            </h1>
            <Link
              href="/gunbuilder"
              className="text-amber-300 hover:text-amber-200 underline"
            >
              Return to Gunbuilder
            </Link>
          </div>
        </div>
      </main>
    );
  }

  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">
          <Link
            href="/gunbuilder"
            className="text-xs text-zinc-400 hover:text-zinc-300 mb-4 inline-block"
          >
            ← Back to Gunbuilder
          </Link>
          <div className="flex items-start justify-between gap-4">
            <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">
                {category.name} <span className="text-amber-300">Parts</span>
              </h1>
              <p className="mt-2 text-sm text-zinc-400 max-w-xl">
                Browse all available {category.name.toLowerCase()} options for
                your build, pulled live from your Ballistic backend.
              </p>
            </div>
            {!loading && !error && parts.length > 0 && (
              <div className="flex gap-2 border border-zinc-800 rounded-md p-1 bg-zinc-950/60">
                <button
                  type="button"
                  onClick={() => setViewMode("card")}
                  className={`px-3 py-1.5 text-xs font-medium rounded transition-colors ${
                    viewMode === "card"
                      ? "bg-zinc-800 text-zinc-50"
                      : "text-zinc-400 hover:text-zinc-300"
                  }`}
                  aria-label="Card view"
                >
                  Card
                </button>
                <button
                  type="button"
                  onClick={() => setViewMode("list")}
                  className={`px-3 py-1.5 text-xs font-medium rounded transition-colors ${
                    viewMode === "list"
                      ? "bg-zinc-800 text-zinc-50"
                      : "text-zinc-400 hover:text-zinc-300"
                  }`}
                  aria-label="List view"
                >
                  List
                </button>
              </div>
            )}
          </div>
        </header>

        {/* Parts Grid/List */}
        <section className="rounded-lg border border-zinc-800 bg-zinc-950/60 p-3 md:p-4">
          {/* Filter + sort toolbar */}
          {!loading && !error && parts.length > 0 && (
            <div className="mb-4 flex flex-col gap-3 md:flex-row md:items-center md:justify-between">
              <div className="text-xs text-zinc-500">
                Showing{" "}
                <span className="text-zinc-200 font-medium">
                  {filteredParts.length}
                </span>{" "}
                of{" "}
                <span className="text-zinc-200 font-medium">
                  {parts.length}
                </span>{" "}
                parts
              </div>
              <div className="flex flex-wrap gap-3">
              <div className="flex items-center gap-2">
                <label htmlFor="part-search" className="text-xs text-zinc-500">
                  Search
                </label>
                <div className="relative">
                  <input
                    id="part-search"
                    type="text"
                    value={searchQuery}
                    onChange={(e) => setSearchQuery(e.target.value)}
                    placeholder={`Search ${category.name.toLowerCase()}...`}
                    className="rounded-md border border-zinc-700 bg-zinc-900/70 text-xs text-zinc-200 px-2 py-1 pr-6 focus:outline-none focus:ring-1 focus:ring-amber-400"
                  />
                  {searchQuery && (
                    <button
                      type="button"
                      onClick={() => setSearchQuery("")}
                      className="absolute right-1 top-1/2 -translate-y-1/2 text-zinc-500 hover:text-zinc-300 text-xs leading-none"
                      aria-label="Clear search"
                    >
                      ×
                    </button>
                  )}
                </div>
              </div>
                <div className="flex items-center gap-2">
                  <label
                    htmlFor="brand-filter"
                    className="text-xs text-zinc-500"
                  >
                    Brand
                  </label>
                  <select
                    id="brand-filter"
                    value={brandFilter}
                    onChange={(e) => setBrandFilter(e.target.value)}
                    className="rounded-md border border-zinc-700 bg-zinc-900/70 text-xs text-zinc-200 px-2 py-1 focus:outline-none focus:ring-1 focus:ring-amber-400"
                  >
                    <option value="all">All brands</option>
                    {availableBrands.map((b) => (
                      <option key={b} value={b}>
                        {b}
                      </option>
                    ))}
                  </select>
                </div>
                <div className="flex items-center gap-2">
                  <label htmlFor="sort-by" className="text-xs text-zinc-500">
                    Sort
                  </label>
                  <select
                    id="sort-by"
                    value={sortBy}
                    onChange={(e) =>
                      setSortBy(e.target.value as SortOption)
                    }
                    className="rounded-md border border-zinc-700 bg-zinc-900/70 text-xs text-zinc-200 px-2 py-1 focus:outline-none focus:ring-1 focus:ring-amber-400"
                  >
                    <option value="relevance">Relevance</option>
                    <option value="price-asc">Price: Low → High</option>
                    <option value="price-desc">Price: High → Low</option>
                    <option value="brand-asc">Brand: A → Z</option>
                  </select>
                </div>
              </div>
            </div>
          )}

          {loading ? (
            <p className="text-sm text-zinc-500 text-center py-8">
              Loading {category.name.toLowerCase()}…
            </p>
          ) : error ? (
            <p className="text-sm text-red-400 text-center py-8">
              {error} — check that the Ballistic API is running.
            </p>
          ) : filteredParts.length === 0 ? (
            <p className="text-sm text-zinc-500 text-center py-8">
              No parts available for this category yet.
            </p>
          ) : viewMode === "card" ? (
            <div className="grid gap-3 md:grid-cols-2 lg:grid-cols-3">
              {filteredParts.map((part) => {
                const isSelected = build[categoryId] === part.id;

                return (
                  <div
                    key={part.id}
                    className={`group relative rounded-md p-3 transition-all duration-200 flex flex-col border ${
                      isSelected
                        ? "border-amber-400/70 bg-amber-400/10 shadow-[0_0_0_1px_rgba(251,191,36,0.25)]"
                        : "border-zinc-700 bg-zinc-900/50 hover:border-amber-400/60 hover:bg-amber-400/10"
                    }`}
                  >
                    <div className="flex justify-between items-center gap-2 mb-3">
                      <div className="flex-1">
                        <div className="text-sm font-semibold text-zinc-50">
                          {part.brand}{" "}
                          <span className="font-normal">— {part.name}</span>
                        </div>
                        {part.notes && (
                          <p className="mt-1 text-xs text-zinc-400 line-clamp-2">
                            {part.notes}
                          </p>
                        )}
                      </div>
                      <div className="text-sm font-semibold text-amber-300 whitespace-nowrap">
                        ${part.price.toFixed(2)}
                      </div>
                    </div>
                    <div className="mt-2 flex gap-2">
                      <Link
                        href={`/gunbuilder/${categoryId}/${part.id}`}
                        className="flex-1 rounded-md border border-zinc-700 bg-zinc-800/50 px-3 py-2 text-xs font-medium text-zinc-300 hover:bg-zinc-700 hover:border-zinc-600 transition-colors text-center"
                      >
                        View Details
                      </Link>
                      <button
                        type="button"
                        onClick={() => handleTogglePart(categoryId, part.id)}
                        className={`flex-1 rounded-md px-3 py-2 text-xs font-semibold transition-colors text-center ${
                          isSelected
                            ? "bg-zinc-800 text-zinc-100 border border-zinc-600 hover:bg-zinc-700"
                            : "bg-amber-400 text-black hover:bg-amber-300"
                        }`}
                      >
                        {isSelected ? "Remove from Build" : "Add to Build"}
                      </button>
                    </div>
                  </div>
                );
              })}
            </div>
          ) : (
            <>
              {/* Header row for list view */}
              <div className="hidden md:grid grid-cols-[minmax(0,3fr)_minmax(0,1fr)_minmax(0,1fr)_auto] gap-4 px-3 pb-2 text-[0.7rem] uppercase tracking-[0.16em] text-zinc-500">
                <span>Part</span>
                <span>Brand</span>
                <span className="text-right">Price</span>
                <span className="text-right pr-2">Actions</span>
              </div>

              <div className="space-y-2">
                {filteredParts.map((part) => {
                  const isSelected = build[categoryId] === part.id;

                  return (
                    <div
                      key={part.id}
                      className={`group relative rounded-md p-3 transition-all duration-200 border ${
                        isSelected
                          ? "border-amber-400/70 bg-amber-400/10 shadow-[0_0_0_1px_rgba(251,191,36,0.25)]"
                          : "border-zinc-700 bg-zinc-900/50 hover:border-amber-400/60 hover:bg-amber-400/10"
                      }`}
                    >
                      <div className="flex flex-col gap-2 md:grid md:grid-cols-[minmax(0,3fr)_minmax(0,1fr)_minmax(0,1fr)_auto] md:items-center md:gap-4">
                        <div className="flex-1 min-w-0">
                          <div className="text-sm font-semibold text-zinc-50">
                            {part.name}
                          </div>
                          {part.notes && (
                            <p className="mt-1 text-xs text-zinc-400 line-clamp-1">
                              {part.notes}
                            </p>
                          )}
                        </div>
                        <div className="text-xs md:text-sm text-zinc-400 md:text-left">
                          {part.brand}
                        </div>
                        <div className="text-sm font-semibold text-amber-300 md:text-right">
                          ${part.price.toFixed(2)}
                        </div>
                        <div className="flex justify-end gap-2">
                          <Link
                            href={`/gunbuilder/${categoryId}/${part.id}`}
                            className="rounded-md border border-zinc-700 bg-zinc-800/50 px-3 py-1.5 text-xs font-medium text-zinc-300 hover:bg-zinc-700 hover:border-zinc-600 transition-colors whitespace-nowrap"
                          >
                            View Details
                          </Link>
                          <button
                            type="button"
                            onClick={() =>
                              handleTogglePart(categoryId, part.id)
                            }
                            className={`rounded-md px-3 py-1.5 text-xs font-semibold transition-colors whitespace-nowrap ${
                              isSelected
                                ? "bg-zinc-800 text-zinc-100 border border-zinc-600 hover:bg-zinc-700"
                                : "bg-amber-400 text-black hover:bg-amber-300"
                            }`}
                          >
                            {isSelected ? "Remove from Build" : "Add to Build"}
                          </button>
                        </div>
                      </div>
                    </div>
                  );
                })}
              </div>
            </>
          )}
        </section>
      </div>
    </main>
  );
}