"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 { PART_ROLE_TO_CATEGORY } from "@/data/partRoleMappings";

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";

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

const STORAGE_KEY = "gunbuilder-build-state";

// Category groups for the main grid
const CATEGORY_GROUPS: {
  id: string;
  label: string;
  description?: string;
  categoryIds: CategoryId[];
}[] = [
  {
    id: "lower-group",
    label: "Lower Receiver Parts",
    description:
      "Everything from the serialized lower to small parts, fire control, and core controls.",
    categoryIds: [
      "lower",
      "completeLower",
      "lowerParts",
      "trigger",
      "grip",
      "safety",
      "buffer",
      "stock",
    ],
  },
  {
    id: "upper-group",
    label: "Upper Receiver Parts",
    description:
      "Barrel, upper, gas system, and the parts that keep the rifle cycling.",
    categoryIds: [
      "upper",
      "completeUpper",
      "bcg",
      "barrel",
      "gasBlock",
      "gasTube",
      "muzzleDevice",
      "suppressor",
      "handguard",
      "chargingHandle",
      "sights",
      "optic",
    ],
  },
  // Optional: future group for accessories/furniture if needed
  // {
  //   id: "accessories-group",
  //   label: "Accessories & Furniture",
  //   description: "Optics, lights, slings, and other supporting gear.",
  //   categoryIds: ["optic", "sights", ...] as CategoryId[],
  // },
];

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 {};
  });
  const [shareStatus, setShareStatus] = useState<string | null>(null);
  const [shareUrl, setShareUrl] = useState<string>("");

  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,
          };
          if (typeof window !== "undefined") {
            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],
  );

  useEffect(() => {
    if (typeof window === "undefined") return;

    // If no parts selected, clear the share URL
    if (Object.keys(build).length === 0) {
      setShareUrl("");
      return;
    }

    try {
      const payload = JSON.stringify(build);
      const encoded = window.btoa(payload);
      const origin = window.location?.origin ?? "";
      const url = `${origin}/gunbuilder/build?build=${encodeURIComponent(
        encoded,
      )}`;
      setShareUrl(url);
    } catch {
      setShareUrl("");
    }
  }, [build]);

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

  // Use group ordering for the summary as well
  const summaryCategoryOrder: CategoryId[] = useMemo(
    () =>
      CATEGORY_GROUPS.flatMap((group) => group.categoryIds).filter(
        (id) => CATEGORIES.some((c) => c.id === id),
      ),
    [],
  );

  const handleShare = async () => {
    if (selectedParts.length === 0) {
      setShareStatus("Add a few parts before sharing your build.");
      return;
    }

    const lines: string[] = [];
    lines.push("Shadow Standard — The Armory Build");
    lines.push("");
    lines.push(`Total: $${totalPrice.toFixed(2)}`);
    lines.push("");

    summaryCategoryOrder.forEach((categoryId) => {
      const cat = CATEGORIES.find((c) => c.id === categoryId);
      if (!cat) return;

      const selectedPartId = build[cat.id];
      const part = parts.find(
        (p) => p.id === selectedPartId && p.categoryId === cat.id,
      );

      if (part) {
        lines.push(
          `${cat.name}: ${part.brand} — ${part.name} ($${part.price.toFixed(
            2,
          )})`,
        );
      } else {
        lines.push(`${cat.name}: [Not selected]`);
      }
    });

    const text = lines.join("\n");

    try {
      await navigator.clipboard.writeText(text);
      setShareStatus("Build summary copied to clipboard.");
    } catch {
      setShareStatus(
        "Could not access clipboard. You can copy from the build summary page.",
      );
    }
  };

  const handleCopyLink = async () => {
    if (!shareUrl) {
      setShareStatus("No shareable link available yet.");
      return;
    }

    try {
      await navigator.clipboard.writeText(shareUrl);
      setShareStatus("Shareable link copied to clipboard.");
    } catch {
      setShareStatus("Could not copy link to clipboard.");
    }
  };

  const handleNativeShare = async () => {
    if (!shareUrl) {
      setShareStatus("No shareable link available yet.");
      return;
    }

    if (navigator.share) {
      try {
        await navigator.share({
          title: "Shadow Standard — The Armory Build",
          text: "Check out my Shadow Standard Armory build.",
          url: shareUrl,
        });
        setShareStatus("Share dialog opened.");
      } catch {
        // User canceled or share failed; keep it quiet but let them know
        setShareStatus("Share canceled or unavailable. You can copy the link instead.");
      }
    } else {
      // Fallback to copying the link
      await handleCopyLink();
    }
  };

  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">
          <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>
        </header>

                {/* Build summary panel */}
                <section className="mb-6 rounded-lg border border-zinc-800 bg-zinc-950/80 p-3 md:p-4 flex flex-col gap-3 md:flex-row md:items-start md:justify-between">
          {/* Left: title + totals + primary actions */}
          <div className="flex flex-col gap-2">
            <h2 className="text-xs font-semibold uppercase tracking-[0.16em] text-amber-300">
              My Build Breakdown
            </h2>
            <div>
              <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 mt-1">
                {selectedParts.length} / {CATEGORIES.length} categories filled
              </div>
            </div>

            {/* Primary actions now live under the total */}
            <div className="mt-2 flex flex-col items-stretch gap-2 sm:flex-row sm:flex-wrap">
              <Link
                href="/gunbuilder/build"
                className={`w-full sm:w-auto 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={handleShare}
                className={`w-full sm:w-auto rounded-md px-3 py-2 text-sm font-semibold transition-colors border ${
                  selectedParts.length === 0
                    ? "bg-zinc-900/80 text-zinc-600 border-zinc-800 cursor-not-allowed"
                    : "bg-zinc-900/80 text-zinc-200 border-zinc-700 hover:bg-zinc-800"
                }`}
                disabled={selectedParts.length === 0}
              >
                Copy Build Summary
              </button>
              <button
                type="button"
                onClick={() => {
                  setBuild({});
                  if (typeof window !== "undefined") {
                    localStorage.removeItem(STORAGE_KEY);
                  }
                }}
                disabled={selectedParts.length === 0}
                className={`w-full sm:w-auto 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>
            </div>
          </div>

          {/* Right: Share Your Build */}
          <div className="flex flex-col gap-3 md:items-end md:text-right md:flex-1">
            {selectedParts.length > 0 && shareUrl && (
              <div className="w-full md:w-auto">
                <h3 className="text-[0.7rem] font-semibold uppercase tracking-[0.16em] text-zinc-400">
                  Share Your Build
                </h3>
                <p className="mt-1 text-[0.7rem] text-zinc-500">
                  Share this link to let others view your build or bookmark it to come
                  back later.
                </p>
                <div className="mt-2 flex flex-col gap-2 md:flex-row md:items-center">
                  <div className="flex-1">
                    <div className="text-[0.65rem] uppercase tracking-[0.16em] text-zinc-500 mb-1">
                      Shareable URL
                    </div>
                    <input
                      type="text"
                      readOnly
                      value={shareUrl}
                      className="w-full rounded-md border border-zinc-700 bg-zinc-950/80 px-2 py-1.5 text-[0.7rem] text-zinc-200 font-mono outline-none focus:ring-1 focus:ring-amber-400"
                    />
                  </div>
                  <div className="flex gap-2 md:flex-none md:mt-5">
                    <button
                      type="button"
                      onClick={handleNativeShare}
                      className="flex-1 md:flex-none rounded-md bg-zinc-900/80 px-3 py-1.5 text-[0.75rem] font-semibold text-zinc-100 border border-zinc-700 hover:bg-zinc-800 hover:border-zinc-500 transition-colors"
                    >
                      Share
                    </button>
                    <button
                      type="button"
                      onClick={handleCopyLink}
                      className="flex-1 md:flex-none rounded-md bg-amber-400 px-3 py-1.5 text-[0.75rem] font-semibold text-black hover:bg-amber-300 transition-colors"
                    >
                      Copy Link
                    </button>
                  </div>
                </div>
              </div>
            )}

            {shareStatus && (
              <p className="mt-1 text-[0.7rem] text-zinc-500">
                {shareStatus}
              </p>
            )}
          </div>
        </section>

        {/* Layout */}
        <section className="rounded-lg border border-zinc-800 bg-zinc-950/60 p-3 md:p-4">
          <p className="mb-4 text-xs text-zinc-500">
            Work top-down through the major sections. Each row shows your
            current pick for that part type, with price and a direct buy
            link—or a quick way to choose a part if you haven&apos;t picked
            one yet.
          </p>

          {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="space-y-6">
              {CATEGORY_GROUPS.map((group) => {
                const groupCategories = CATEGORIES.filter((c) =>
                  group.categoryIds.includes(c.id as CategoryId),
                );

                if (groupCategories.length === 0) {
                  return null;
                }

                return (
                  <div key={group.id} className="space-y-3">
                    <div className="flex items-baseline justify-between gap-2">
                      <div>
                        <h2 className="text-sm font-semibold text-zinc-100">
                          {group.label}
                        </h2>
                        {group.description && (
                          <p className="text-xs text-zinc-500 mt-1 max-w-xl">
                            {group.description}
                          </p>
                        )}
                      </div>
                    </div>

                    <div className="overflow-x-auto rounded-md border border-zinc-800 bg-zinc-950/80">
                      <table className="min-w-full text-xs md:text-sm">
                        <thead>
                          <tr className="border-b border-zinc-800 bg-zinc-900/60">
                            <th className="px-3 py-2 text-left font-semibold text-zinc-400">
                              Component / Part Type
                            </th>
                            <th className="px-3 py-2 text-left font-semibold text-zinc-400">
                              Brand
                            </th>
                            <th className="px-3 py-2 text-right font-semibold text-zinc-400">
                              Price
                            </th>
                            <th className="px-3 py-2 text-right font-semibold text-zinc-400">
                              Sale Price
                            </th>
                            <th className="px-3 py-2 text-left font-semibold text-zinc-400">
                              Caliber
                            </th>
                            <th className="px-3 py-2 text-right font-semibold text-zinc-400">
                              Buy / Choose
                            </th>
                          </tr>
                        </thead>
                        <tbody>
                          {groupCategories.map((category) => {
                            const categoryParts =
                              partsByCategory[category.id] ?? [];
                            const selectedPartId = build[category.id];
                            const selectedPart = categoryParts.find(
                              (p) => p.id === selectedPartId,
                            );
                            const hasParts = categoryParts.length > 0;

                            return (
                              <tr
                                key={category.id}
                                className="border-t border-zinc-900 hover:bg-zinc-900/60 transition-colors"
                              >
                                {/* Component / Part Type */}
                                <td className="px-3 py-2 align-top">
                                  <div className="font-medium text-zinc-100">
                                    {category.name}
                                  </div>
                                  {selectedPart ? (
                                    <div className="text-[0.7rem] text-zinc-500 line-clamp-1">
                                      {selectedPart.name}
                                    </div>
                                  ) : hasParts ? (
                                    <div className="text-[0.7rem] text-zinc-600">
                                      No part selected
                                    </div>
                                  ) : (
                                    <div className="text-[0.7rem] text-zinc-600">
                                      No parts available yet
                                    </div>
                                  )}
                                </td>

                                {/* Brand */}
                                <td className="px-3 py-2 align-top text-zinc-300">
                                  {selectedPart ? selectedPart.brand : "—"}
                                </td>

                                {/* Price */}
                                <td className="px-3 py-2 align-top text-right text-amber-300">
                                  {selectedPart
                                    ? `$${selectedPart.price.toFixed(2)}`
                                    : "—"}
                                </td>

                                {/* Sale Price (placeholder until we wire through sale/original) */}
                                <td className="px-3 py-2 align-top text-right text-zinc-400">
                                  {/* TODO: wire in sale/original prices from backend */}
                                  {selectedPart ? "—" : "—"}
                                </td>

                                {/* Caliber (placeholder for now) */}
                                <td className="px-3 py-2 align-top text-zinc-400">
                                  {/* TODO: wire in caliber from ProductSummaryDto when available */}
                                  —
                                </td>

                                {/* Buy / Choose */}
                                <td className="px-3 py-2 align-top">
                                  <div className="flex justify-end gap-2">
                                    {selectedPart && selectedPart.url ? (
                                      <>
                                        <Link
                                          href={`/gunbuilder/${category.id}`}
                                          className="hidden md:inline-flex rounded-md border border-zinc-700 bg-zinc-900/70 px-2.5 py-1 text-[0.7rem] font-medium text-zinc-300 hover:bg-zinc-800 hover:border-zinc-600 transition-colors"
                                        >
                                          Change Part
                                        </Link>
                                        <a
                                          href={selectedPart.url}
                                          target="_blank"
                                          rel="noreferrer"
                                          className="inline-flex rounded-md bg-amber-400 px-2.5 py-1 text-[0.7rem] font-semibold text-black hover:bg-amber-300 transition-colors"
                                        >
                                          Buy
                                        </a>
                                      </>
                                    ) : hasParts ? (
                                      <Link
                                        href={`/gunbuilder/${category.id}`}
                                        className="inline-flex rounded-md border border-zinc-700 bg-zinc-900/70 px-2.5 py-1 text-[0.7rem] font-medium text-zinc-200 hover:bg-zinc-800 hover:border-zinc-600 transition-colors"
                                        onClick={() => {
                                          // If you want to pre-select something later, you can handle here.
                                        }}
                                      >
                                        Choose a Part
                                      </Link>
                                    ) : (
                                      <span className="text-[0.7rem] text-zinc-600">
                                        —
                                      </span>
                                    )}
                                  </div>
                                </td>
                              </tr>
                            );
                          })}
                        </tbody>
                      </table>
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </section>

        {/* What's New */}
        <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>
              • Grouped layout for lower and upper receiver parts so you can see
              at a glance which sections 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>

        {/* Roadmap */}
        <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 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 and furniture</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>
  );
}