"use client";

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

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

const STORAGE_KEY = "gunbuilder-build-state";

// Encode build state to URL-friendly string
function encodeBuildState(build: BuildState): string {
  const entries = Object.entries(build)
    .filter(([_, partId]) => partId)
    .map(([categoryId, partId]) => `${categoryId}:${partId}`)
    .join(",");
  return btoa(entries);
}

// Decode URL string to build state
function decodeBuildState(encoded: string): BuildState {
  try {
    const decoded = atob(encoded);
    const build: BuildState = {};
    decoded.split(",").forEach((entry) => {
      const [categoryId, partId] = entry.split(":");
      if (categoryId && partId) {
        build[categoryId as CategoryId] = partId;
      }
    });
    return build;
  } catch {
    return {};
  }
}

export default function BuildDetailsPage() {
  const searchParams = useSearchParams();
  const router = useRouter();
  const [build, setBuild] = useState<BuildState>({});
  const [shareUrl, setShareUrl] = useState<string>("");
  const [copied, setCopied] = useState(false);

  // Load build from URL params or localStorage
  useEffect(() => {
    const buildParam = searchParams.get("build");
    if (buildParam) {
      const decoded = decodeBuildState(buildParam);
      setBuild(decoded);
      // Also save to localStorage
      localStorage.setItem(STORAGE_KEY, JSON.stringify(decoded));
    } else if (typeof window !== "undefined") {
      // Load from localStorage
      const stored = localStorage.getItem(STORAGE_KEY);
      if (stored) {
        try {
          const parsed = JSON.parse(stored);
          setBuild(parsed);
        } catch {
          // Invalid stored data
        }
      }
    }
  }, [searchParams]);

  // Generate shareable URL
  useEffect(() => {
    if (typeof window !== "undefined" && Object.keys(build).length > 0) {
      const encoded = encodeBuildState(build);
      const url = `${window.location.origin}/gunbuilder/build?build=${encoded}`;
      setShareUrl(url);
    }
  }, [build]);

  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 handleCopyLink = async () => {
    if (shareUrl) {
      try {
        await navigator.clipboard.writeText(shareUrl);
        setCopied(true);
        setTimeout(() => setCopied(false), 2000);
      } catch (err) {
        console.error("Failed to copy:", err);
      }
    }
  };

  const handleShare = async () => {
    if (navigator.share && shareUrl) {
      try {
        await navigator.share({
          title: "My AR-15 Build",
          text: `Check out my AR-15 build: $${totalPrice.toFixed(2)}`,
          url: shareUrl,
        });
      } catch (err) {
        // User cancelled or share failed, fall back to copy
        handleCopyLink();
      }
    } else {
      handleCopyLink();
    }
  };

  if (selectedParts.length === 0) {
    return (
      <main className="min-h-screen bg-black text-zinc-50">
        <div className="mx-auto max-w-4xl px-4 py-6 lg:py-10">
          <div className="text-center">
            <h1 className="text-2xl font-semibold text-zinc-50 mb-4">
              No Build Selected
            </h1>
            <p className="text-sm text-zinc-400 mb-6">
              You need to select at least one part to view your build.
            </p>
            <Link
              href="/gunbuilder"
              className="inline-block rounded-md border border-amber-400/60 bg-amber-400/10 px-4 py-2 text-sm font-medium text-amber-200 hover:bg-amber-400/15 transition-colors"
            >
              Go 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 flex-col gap-4 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">
                Build <span className="text-amber-300">Summary</span>
              </h1>
              <p className="mt-2 text-sm text-zinc-400 max-w-xl">
                Review your build, purchase parts from our affiliate partners, or
                share your build with others.
              </p>
            </div>

            <div className="mt-3 md:mt-0">
              <div className="text-xs text-zinc-400">Total Build Price</div>
              <div className="text-3xl font-semibold text-amber-300">
                ${totalPrice.toFixed(2)}
              </div>
              <div className="text-xs text-zinc-500">
                {selectedParts.length} / {CATEGORIES.length} parts selected
              </div>
            </div>
          </div>
        </header>

        {/* Share Section */}
        <section className="mb-6 rounded-lg border border-zinc-800 bg-zinc-950/60 p-4">
          <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
            <div className="flex-1">
              <h2 className="text-xs font-semibold tracking-[0.16em] uppercase text-zinc-400 mb-2">
                Share Your Build
              </h2>
              <p className="text-sm text-zinc-400">
                Share this link to let others view your build or bookmark it to
                come back later.
              </p>
            </div>
            <div className="flex gap-2">
              <button
                type="button"
                onClick={handleShare}
                className="rounded-md border border-zinc-700 bg-zinc-900/50 px-4 py-2 text-sm font-medium text-zinc-300 hover:bg-zinc-800 hover:border-zinc-600 transition-colors"
              >
                Share
              </button>
              <button
                type="button"
                onClick={handleCopyLink}
                className={`rounded-md border px-4 py-2 text-sm font-medium transition-colors ${
                  copied
                    ? "border-green-500 bg-green-500/10 text-green-400"
                    : "border-zinc-700 bg-zinc-900/50 text-zinc-300 hover:bg-zinc-800 hover:border-zinc-600"
                }`}
              >
                {copied ? "Copied!" : "Copy Link"}
              </button>
            </div>
          </div>
          {shareUrl && (
            <div className="mt-3 p-3 rounded-md bg-zinc-900/50 border border-zinc-800">
              <p className="text-xs text-zinc-500 mb-1">Shareable URL:</p>
              <p className="text-xs text-zinc-400 break-all font-mono">
                {shareUrl}
              </p>
            </div>
          )}
        </section>

        {/* Build Parts */}
        <section className="rounded-lg border border-zinc-800 bg-zinc-950/60 p-4 md:p-6">
          <h2 className="text-xs font-semibold tracking-[0.16em] uppercase text-zinc-400 mb-4">
            Selected Parts
          </h2>

          <div className="space-y-4">
            {CATEGORIES.map((category) => {
              const selectedPartId = build[category.id];
              const part = PARTS.find(
                (p) => p.id === selectedPartId && p.categoryId === category.id,
              );

              return (
                <div
                  key={category.id}
                  className="border border-zinc-800 rounded-md p-4 bg-zinc-900/30"
                >
                  <div className="flex items-start justify-between gap-4">
                    <div className="flex-1">
                      <div className="text-[0.7rem] uppercase tracking-[0.16em] text-zinc-500 mb-2">
                        {category.name}
                      </div>
                      {part ? (
                        <>
                          <div className="text-lg font-semibold text-zinc-50 mb-1">
                            <span className="text-zinc-400">{part.brand}</span>{" "}
                            {part.name}
                          </div>
                          {part.notes && (
                            <p className="text-sm text-zinc-400 mt-1">
                              {part.notes}
                            </p>
                          )}
                          <div className="mt-3 flex gap-2">
                            <a
                              href={part.affiliateUrl}
                              target="_blank"
                              rel="noopener noreferrer"
                              className="inline-flex items-center gap-2 rounded-md border border-amber-400/60 bg-amber-400/10 px-4 py-2 text-sm font-medium text-amber-200 hover:bg-amber-400/15 transition-colors"
                            >
                              Purchase from Retailer
                              <svg
                                className="w-4 h-4"
                                fill="none"
                                stroke="currentColor"
                                viewBox="0 0 24 24"
                              >
                                <path
                                  strokeLinecap="round"
                                  strokeLinejoin="round"
                                  strokeWidth={2}
                                  d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"
                                />
                              </svg>
                            </a>
                            <Link
                              href={`/gunbuilder/${category.id}/${part.id}`}
                              className="inline-flex items-center rounded-md border border-zinc-700 bg-zinc-900/50 px-4 py-2 text-sm font-medium text-zinc-300 hover:bg-zinc-800 hover:border-zinc-600 transition-colors"
                            >
                              View Details
                            </Link>
                          </div>
                        </>
                      ) : (
                        <div className="text-sm text-zinc-600">
                          Not selected
                        </div>
                      )}
                    </div>
                    {part && (
                      <div className="text-right">
                        <div className="text-2xl font-semibold text-amber-300">
                          ${part.price.toFixed(2)}
                        </div>
                      </div>
                    )}
                  </div>
                </div>
              );
            })}
          </div>
        </section>

        {/* Actions */}
        <div className="mt-6 flex flex-col gap-3 sm:flex-row sm:justify-between">
          <Link
            href="/gunbuilder"
            className="rounded-md border border-zinc-700 bg-zinc-900/50 px-6 py-3 text-sm font-medium text-zinc-300 hover:bg-zinc-800 hover:border-zinc-600 transition-colors text-center"
          >
            Edit Build
          </Link>
          <div className="flex gap-3">
            <button
              type="button"
              onClick={() => {
                localStorage.removeItem(STORAGE_KEY);
                router.push("/gunbuilder");
              }}
              className="rounded-md border border-zinc-700 bg-zinc-900/50 px-6 py-3 text-sm font-medium text-zinc-300 hover:bg-zinc-800 hover:border-zinc-600 transition-colors"
            >
              Clear Build
            </button>
          </div>
        </div>
      </div>
    </main>
  );
}

