"use client";

import Link from "next/link";
import { useEffect, useMemo, useRef, useState } from "react";
import { AnimatePresence, motion, useScroll, useTransform } from "motion/react";
import { Gauge, RefreshCw } from "lucide-react";
import Flag from "react-flagkit";
import { cn } from "@/lib/utils";
import { useServerStock } from "@/hooks/useServerStock";
import {
  type BillingCycle,
  type GameHostTheme,
  type TierSlug,
  gameHostingList,
} from "@/lib/data/game-hosting";
import { ProductCard } from "./ProductCard";
import PanelSection from "@/app/home/PanelSection";

type GameHostClientProps = {
  game: GameHostTheme;
};

const noiseStyle = {
  backgroundImage: `url("data:image/svg+xml,%3Csvg viewBox='0 0 256 256' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='noise'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='4' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23noise)'/%3E%3C/svg%3E")`,
  backgroundSize: "128px 128px",
};

function CpuBrandLogo({ cpuDetail }: { cpuDetail: string }) {
  const lower = cpuDetail.toLowerCase();
  const brand = lower.includes("intel") ? "intel" : lower.includes("amd") ? "amd" : null;
  if (!brand) return null;

  return (
    <img
      src={`/asset/images/icons/${brand}.svg`}
      alt={brand.toUpperCase()}
      className="h-10 w-auto object-contain opacity-80 tech-icon-filter"
    />
  );
}

function parseRamGB(ram: string) {
  const normalized = ram.toLowerCase();
  const value = Number.parseFloat(normalized);
  if (Number.isNaN(value)) return 1;
  return normalized.includes("mb") ? Math.max(1, Math.ceil(value / 1024)) : value;
}

function PackageSkeletonGrid() {
  return (
    <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-5 w-full">
      {Array.from({ length: 4 }).map((_, index) => (
        <motion.div
          key={index}
          initial={{ opacity: 0, y: 12 }}
          animate={{ opacity: 1, y: 0 }}
          exit={{ opacity: 0 }}
          transition={{ duration: 0.25, delay: index * 0.04 }}
          className="rounded-2xl border border-border bg-surface p-5"
        >
          <div className="space-y-4">
            <div className="h-5 w-2/3 rounded bg-elevated animate-pulse" />
            <div className="h-4 w-full rounded bg-border animate-pulse" />
            <div className="grid grid-cols-2 gap-3">
              {Array.from({ length: 6 }).map((__, specIndex) => (
                <div key={specIndex} className="space-y-2">
                  <div className="h-3 w-14 rounded bg-border animate-pulse" />
                  <div className="h-4 w-20 rounded bg-elevated animate-pulse" />
                </div>
              ))}
            </div>
            <div className="h-11 rounded-xl bg-elevated animate-pulse" />
          </div>
        </motion.div>
      ))}
    </div>
  );
}

export default function GameHostClient({ game }: GameHostClientProps) {
  const tierKeys = useMemo(() => Object.keys(game.tiers) as TierSlug[], [game.tiers]);
  const [activeTier, setActiveTier] = useState<TierSlug>(tierKeys[0] ?? "core");
  const [cycle, setCycle] = useState<BillingCycle>("monthly");
  const [selectedSoftwareId, setSelectedSoftwareId] = useState(game.defaultSoftware ?? game.softwareOptions?.[0]?.id);
  const [selectedLocationId, setSelectedLocationId] = useState(game.defaultLocation ?? game.locationOptions[0]?.id);
  const [isVisible, setIsVisible] = useState(false);
  const [isTierSwitching, setIsTierSwitching] = useState(false);

  const { getStockCount, refreshStock, isLoading: isStockLoading } = useServerStock();
  const [isRefreshing, setIsRefreshing] = useState(false);

  const containerRef = useRef<HTMLDivElement>(null);
  const { scrollYProgress } = useScroll({ target: containerRef, offset: ["start start", "end start"] });
  const headerOpacity = useTransform(scrollYProgress, [0, 0.18], [1, 0]);
  const headerY = useTransform(scrollYProgress, [0, 0.18], [0, -40]);

  useEffect(() => {
    const timer = setTimeout(() => setIsVisible(true), 100);
    return () => clearTimeout(timer);
  }, []);

  useEffect(() => {
    const params = new URLSearchParams(window.location.search);
    const plan = params.get("plan") as TierSlug | null;
    const software = params.get("software");
    const location = params.get("location");

    setActiveTier(plan && plan in game.tiers ? plan : tierKeys[0] ?? "core");
    setSelectedSoftwareId(
      software && game.softwareOptions?.some((item) => item.id === software)
        ? software
        : game.defaultSoftware ?? game.softwareOptions?.[0]?.id
    );
    setSelectedLocationId(
      location && game.locationOptions.some((item) => item.id === location)
        ? location
        : game.defaultLocation ?? game.locationOptions[0]?.id
    );
  }, [game, tierKeys]);

  const currentTierData = game.tiers[activeTier] ?? game.tiers[tierKeys[0]];
  const selectedSoftware = game.softwareOptions?.find((software) => software.id === selectedSoftwareId);
  const selectedLocation = game.locationOptions.find((location) => location.id === selectedLocationId) ?? game.locationOptions[0];

  const updateQueryParam = (key: string, value: string) => {
    const url = new URL(window.location.href);
    url.searchParams.set(key, value);
    window.history.replaceState({}, "", url.toString());
  };

  const handleTierChange = (newTier: TierSlug) => {
    if (newTier === activeTier) return;
    setIsTierSwitching(true);
    setActiveTier(newTier);
    updateQueryParam("plan", newTier);
    setTimeout(() => setIsTierSwitching(false), 350);
  };

  const handleRefreshClick = async () => {
    setIsRefreshing(true);
    await refreshStock();
    setTimeout(() => setIsRefreshing(false), 600);
  };

  return (
    <main
      ref={containerRef}
      className={cn(
        "relative flex flex-col items-center w-full min-h-screen bg-base text-content transition-colors duration-700 font-sans selection:bg-accent-hover/30 overflow-x-hidden",
        isVisible ? "opacity-100" : "opacity-0"
      )}
    >
      <div className="absolute inset-x-0 top-0 h-[600px] lg:h-[800px] z-0 pointer-events-none overflow-hidden [-webkit-mask-image:linear-gradient(to_bottom,white_40%,transparent_100%)] mask-[linear-gradient(to_bottom,white_40%,transparent_100%)]">
        <motion.img
          key={game.slug}
          src={game.heroImage}
          alt=""
          initial={{ opacity: 0, scale: 1.04 }}
          animate={{ opacity: 0.22, scale: 1 }}
          transition={{ duration: 0.8 }}
          className="absolute inset-0 h-full w-full object-cover blur-sm"
        />
        <div className="absolute inset-0 bg-base/75 transition-colors duration-700" />
        <div className="absolute inset-0 transition-colors duration-700" style={{ background: game.radial }} />
      </div>
      <div className="fixed inset-0 opacity-[0.025] pointer-events-none z-0" style={noiseStyle} />

      <div className="relative z-10 w-full max-w-7xl px-4 md:px-6 pt-32 pb-24">
        <motion.div
          style={{ opacity: headerOpacity, y: headerY }}
          className="flex flex-col items-center text-center mb-16"
        >
          <div className="flex items-center justify-center gap-3 mb-6">
            <span className="block h-0.5 w-6 bg-accent-hover rounded-full" />
            <p className="text-xs font-bold uppercase tracking-widest text-accent-hover">
              {game.eyebrow}
            </p>
            <span className="block h-0.5 w-6 bg-accent-hover rounded-full" />
          </div>
          <h1 className="text-5xl md:text-6xl lg:text-7xl font-semibold tracking-tight text-content leading-[1.05] mb-5 transition-colors duration-700">
            {game.title} <br />
            <span className={game.accentClass}>{game.accentTitle}</span>
          </h1>
          <p className="text-content-dim text-[1rem] md:text-lg max-w-2xl leading-relaxed transition-colors duration-700">
            {game.description}
          </p>
        </motion.div>

        <div className="mb-8 flex flex-wrap justify-center gap-4">
          {gameHostingList.map((item) => {
            const isActive = item.slug === game.slug;
            return (
              <Link
                key={item.slug}
                href={item.href}
                className={cn(
                  "group flex items-center gap-2 px-3 py-2 rounded-xl border transition-all duration-300",
                  isActive
                    ? "border-accent-hover/40 bg-accent/10 text-content"
                    : "border-border bg-surface text-content-dim hover:border-border-hover hover:bg-elevated hover:text-content"
                )}
              >
                <img
                  src={item.navImage}
                  alt=""
                  className="h-8 w-8 object-contain transition-transform duration-300 group-hover:scale-110"
                />
                <span className="text-sm font-semibold">{item.shortLabel}</span>
              </Link>
            );
          })}
        </div>

        <div className="sticky top-24 z-40 w-full mb-8 flex flex-col items-center gap-4">
          <div className="flex justify-center bg-surface/90 backdrop-blur-xl border border-border rounded-xl shadow-2xl p-1.5 gap-1 overflow-x-auto max-w-full transition-colors duration-700">
            {tierKeys.map((tierKey) => {
              const isActive = activeTier === tierKey;
              const tier = game.tiers[tierKey];
              if (!tier) return null;

              return (
                <button
                  key={tierKey}
                  onClick={() => handleTierChange(tierKey)}
                  className={cn(
                    "relative flex items-center gap-2 px-5 py-2.5 rounded-lg text-sm font-semibold transition-all duration-300 min-w-max",
                    isActive ? "bg-accent text-white" : "text-content-dim hover:text-content hover:bg-elevated"
                  )}
                >
                  <span>{tier.label}</span>
                  {tier.badge && (
                    <span
                      className={cn(
                        "px-1.5 py-0.5 rounded text-[9px] uppercase font-bold tracking-wide transition-colors duration-300",
                        isActive ? "bg-white/20 text-white" : "bg-elevated text-content-muted"
                      )}
                    >
                      {tier.badge}
                    </span>
                  )}
                </button>
              );
            })}
          </div>

          {currentTierData && (
            <motion.div
              key={`${game.slug}-${activeTier}`}
              initial={{ opacity: 0, y: -8 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.25 }}
              className="flex flex-col md:flex-row items-center gap-3 md:gap-6 bg-surface/90 px-5 py-3 rounded-xl border border-border backdrop-blur-md transition-colors duration-700"
            >
              <span className="text-sm text-content-muted border-b md:border-b-0 md:border-r border-border pb-2 md:pb-0 md:pr-6 text-center md:text-left transition-colors duration-700">
                {currentTierData.desc}
              </span>
              <div className="flex items-center gap-2.5">
                <CpuBrandLogo cpuDetail={currentTierData.cpuDetail} />
                <div className="text-left">
                  <p className="text-[10px] font-bold text-content-subtle uppercase tracking-widest transition-colors duration-700">Powered By</p>
                  <p className="text-sm font-semibold text-content flex items-center gap-2 transition-colors duration-700">
                    {currentTierData.cpuDetail}
                    <span className="hidden sm:inline-flex items-center gap-1 px-1.5 py-0.5 rounded bg-elevated border border-border text-[10px] text-content-muted font-mono transition-colors duration-700">
                      <Gauge className="w-3 h-3" /> {currentTierData.ghz}
                    </span>
                  </p>
                </div>
              </div>
              <div className="hidden md:block w-px h-7 bg-border transition-colors duration-700" />
              <button
                onClick={handleRefreshClick}
                disabled={isRefreshing || isStockLoading}
                className="flex items-center gap-2 text-xs font-semibold text-accent-text hover:text-accent-hover transition-colors disabled:opacity-40"
              >
                <RefreshCw className={cn("w-3.5 h-3.5", (isRefreshing || isStockLoading) && "animate-spin")} />
                {isRefreshing || isStockLoading ? "Checking..." : "Refresh"}
              </button>
            </motion.div>
          )}
        </div>

        <div className="mb-8 flex flex-col lg:flex-row items-center justify-between gap-4">
          <div className="flex flex-wrap items-center justify-center gap-2">
            {game.locationOptions.map((location) => {
              const isActive = location.id === selectedLocationId;
              return (
                <button
                  key={location.id}
                  onClick={() => {
                    setSelectedLocationId(location.id);
                    updateQueryParam("location", location.id);
                  }}
                  className={cn(
                    "flex items-center gap-2 px-4 py-2 rounded-xl border text-sm font-semibold transition-all duration-300",
                    isActive
                      ? "border-accent-hover/40 bg-accent/10 text-content"
                      : "border-border bg-surface text-content-muted hover:text-content hover:bg-elevated"
                  )}
                >
                  <Flag country={location.countryCode} size={16} />
                  <span>{location.label}</span>
                </button>
              );
            })}
          </div>

          <div className="flex items-center gap-2 rounded-xl bg-elevated/90 border border-border p-1 transition-colors duration-700">
            {(["monthly", "annually"] as BillingCycle[]).map((item) => (
              <button
                key={item}
                onClick={() => setCycle(item)}
                className={cn(
                  "px-4 py-2 rounded-lg text-sm font-semibold transition-all duration-300",
                  cycle === item ? "bg-accent text-white" : "text-content-muted hover:text-content"
                )}
              >
                {item === "monthly" ? "Monthly" : "Annually"}
              </button>
            ))}
          </div>
        </div>

        {game.softwareOptions && (
          <div className="mb-10 grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-3">
            {game.softwareOptions.map((software) => {
              const isActive = software.id === selectedSoftwareId;
              return (
                <button
                  key={software.id}
                  onClick={() => {
                    setSelectedSoftwareId(software.id);
                    updateQueryParam("software", software.id);
                  }}
                  className={cn(
                    "group text-left rounded-xl border p-4 transition-all duration-300",
                    isActive
                      ? "border-accent-hover/40 bg-accent/10"
                      : "border-border bg-surface hover:border-border-hover hover:bg-elevated"
                  )}
                >
                  <div className="flex items-center gap-2 mb-2">
                    {software.image && <img src={software.image} alt="" className="w-5 h-5 object-contain" />}
                    <span className="text-sm font-semibold text-content transition-colors duration-700">{software.label}</span>
                  </div>
                  <p className="text-xs text-content-subtle leading-relaxed transition-colors duration-700">{software.description}</p>
                </button>
              );
            })}
          </div>
        )}

        <AnimatePresence mode="wait">
          {isTierSwitching ? (
            <motion.div key="loading" initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}>
              <PackageSkeletonGrid />
            </motion.div>
          ) : currentTierData ? (
            <motion.div
              key="content"
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-5 w-full"
            >
              <AnimatePresence>
                {currentTierData.plans.map((plan, index) => {
                  const stockStatus = getStockCount(activeTier, parseRamGB(plan.specs.ram));

                  return (
                    <ProductCard
                      key={plan.id}
                      plan={plan}
                      tierColor={currentTierData.color}
                      stockStatus={stockStatus}
                      isLoadingStock={isStockLoading}
                      index={index}
                      cycle={cycle}
                      selectedSoftware={selectedSoftware}
                      selectedLocation={selectedLocation}
                      billingConfig={game.billingConfig}
                    />
                  );
                })}
              </AnimatePresence>
            </motion.div>
          ) : null}
        </AnimatePresence>
      </div>
      <PanelSection />
    </main>
  );
}