"use client";

import { useState, useEffect, useRef } from "react";
import { motion, AnimatePresence } from "framer-motion";
import Link from "next/link";
import { Zap, Search, Gamepad2, Tv, Ticket, Smartphone, Swords, LayoutGrid, Link as LinkIcon } from "lucide-react";
import { fetchGamesClient, type GameItem } from "@/lib/api";

const CATEGORIES = [
  { key: "all", label: "Semua", icon: LayoutGrid },
  { key: "game", label: "Game", icon: Gamepad2 },
  { key: "streaming", label: "Streaming", icon: Tv },
  { key: "voucher", label: "Voucher", icon: Ticket },
  { key: "premium_app", label: "Premium Apps", icon: Smartphone },
  { key: "joki", label: "Joki", icon: Swords },
];

function formatRupiah(n: number) {
  return `Rp ${n.toLocaleString("id-ID")}`;
}

const PUBLISHERS: Record<string, string> = {
  "Mobile Legends B": "Moonton",
  "Mobile Legends A": "Moonton",
  "Mobile Legends (Global)": "Moonton",
  "Free Fire": "Garena",
  "Free Fire Max": "Garena",
  "Genshin Impact": "HoYoverse",
  "Honkai Star Rail": "HoYoverse",
  "Valorant": "Riot Games",
  "League of Legends": "Riot Games",
  "PUBG Mobile (ID)": "Tencent Games",
  "PUBG Mobile (GLOBAL)": "Tencent Games",
  "Call of Duty Mobile": "Activision",
  "One Punch Man": "FingerFun",
  "Tower of Fantasy": "Hotta Studio",
  "Blood Strike": "NetEase",
  "Echo of Soul - Link": "Papaya Play",
};

export default function GameGrid() {
  const [activeCategory, setActiveCategory] = useState("all");
  const [searchQuery, setSearchQuery] = useState("");
  const [allGames, setAllGames] = useState<GameItem[]>([]);
  const [loading, setLoading] = useState(true);
  const isMounted = useRef(true);

  // Fetch ALL games once, then filter client-side
  useEffect(() => {
    isMounted.current = true;
    setLoading(true);
    fetchGamesClient("all")
      .then((data) => {
        if (isMounted.current) setAllGames(data);
      })
      .catch(() => {})
      .finally(() => {
        if (isMounted.current) setLoading(false);
      });
    return () => { isMounted.current = false; };
  }, []);

  // Client-side filtering to fix the tab bug
  const filtered = allGames.filter((g) => {
    const matchCat = activeCategory === "all" || g.category === activeCategory;
    const matchSearch = !searchQuery || g.name.toLowerCase().includes(searchQuery.toLowerCase());
    return matchCat && matchSearch;
  });

  return (
    <section id="products" className="mt-14">
      <div className="flex flex-col md:flex-row md:items-end md:justify-between gap-4 mb-6">
        <div>
          <h2 className="font-heading text-xl md:text-2xl font-bold text-white uppercase tracking-wide">
            Semua Produk
          </h2>
          <p className="text-sm text-muted mt-1">
            <span className="text-primary font-semibold">{filtered.length}</span> layanan tersedia — data realtime dari server
          </p>
        </div>
        <div className="relative max-w-sm w-full">
          <Search size={16} className="absolute left-3.5 top-1/2 -translate-y-1/2 text-muted" />
          <input
            type="text"
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            placeholder="Cari game atau voucher..."
            className="w-full bg-dark-surface border border-dark-border rounded-xl px-4 py-2.5 pl-10 text-sm text-white placeholder-muted focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary/30 transition-all"
          />
        </div>
      </div>

      {/* Category Tabs */}
      <div className="flex gap-2 overflow-x-auto pb-3 mb-5 -mx-4 px-4 scrollbar-hide">
        {CATEGORIES.map((cat) => {
          const isActive = activeCategory === cat.key;
          const count = cat.key === "all" ? allGames.length : allGames.filter(g => g.category === cat.key).length;
          const Icon = cat.icon;
          return (
            <button
              key={cat.key}
              onClick={() => setActiveCategory(cat.key)}
              className={`flex items-center gap-2 px-5 py-2.5 rounded-full text-sm font-bold whitespace-nowrap transition-all duration-300 ${
                isActive
                  ? "bg-primary text-dark shadow-glow-sm"
                  : "bg-dark-surface2 text-white hover:bg-dark-surface"
              }`}
            >
              <Icon size={14} />
              {cat.label}
              {count > 0 && (
                <span className={`text-[10px] px-1.5 py-0.5 rounded-full ${isActive ? "bg-white/20" : "bg-dark-surface2"}`}>
                  {count}
                </span>
              )}
            </button>
          );
        })}
      </div>

      {/* Loading skeleton */}
      {loading ? (
        <div className="grid grid-cols-3 sm:grid-cols-4 md:grid-cols-5 lg:grid-cols-6 gap-2 sm:gap-3 lg:gap-4">
          {Array.from({ length: 18 }).map((_, i) => (
            <div key={i} className="bg-dark-surface rounded-xl sm:rounded-2xl border border-dark-border overflow-hidden animate-pulse">
              <div className="w-full aspect-[4/5] bg-dark-surface2" />
              <div className="p-2 sm:p-3 space-y-2">
                <div className="h-3 bg-dark-surface2 rounded w-3/4" />
                <div className="h-2 bg-dark-surface2 rounded w-1/2" />
              </div>
            </div>
          ))}
        </div>
      ) : (
        <AnimatePresence mode="wait">
          <motion.div
            key={activeCategory + searchQuery}
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            transition={{ duration: 0.2 }}
            className="grid grid-cols-3 sm:grid-cols-4 md:grid-cols-5 lg:grid-cols-6 gap-2 sm:gap-3 lg:gap-4"
          >
            {filtered.map((game, i) => (
              <motion.div
                key={game.slug}
                initial={{ opacity: 0, y: 15 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ delay: Math.min(i * 0.02, 0.4), duration: 0.3 }}
              >
                <Link
                  href={`/${game.slug}`}
                  className="group block bg-dark-surface rounded-xl sm:rounded-2xl border border-dark-border overflow-hidden transition-all duration-300 hover:border-primary/40 hover:shadow-glow-sm hover:-translate-y-1"
                >
                  <div className="relative w-full aspect-[4/5] bg-dark-surface2 overflow-hidden">
                    <img
                      src={game.icon}
                      alt={game.name}
                      className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"
                      loading="lazy"
                      onError={(e) => { (e.target as HTMLImageElement).style.display = "none"; }}
                    />
                    <div className="absolute inset-0 bg-gradient-to-t from-dark-surface/90 via-transparent to-transparent opacity-80" />
                    
                    {/* Orange Link Icon (Top Left) */}
                    <div className="absolute top-1.5 left-1.5 sm:top-2 sm:left-2">
                      <div className="w-4 h-4 sm:w-5 sm:h-5 rounded sm:rounded-md bg-primary flex items-center justify-center shadow-md shadow-primary/20">
                        <LinkIcon size={10} className="text-dark-surface" />
                      </div>
                    </div>
                  </div>
                  <div className="p-2 sm:p-3 bg-dark-surface">
                    <h3 className="text-[10px] sm:text-xs font-bold text-white truncate group-hover:text-primary transition-colors">
                      {game.name}
                    </h3>
                    <p className="text-[8px] sm:text-[10px] text-muted truncate mt-0.5">
                      {PUBLISHERS[game.name] || "Publisher"}
                    </p>
                  </div>
                </Link>
              </motion.div>
            ))}
          </motion.div>
        </AnimatePresence>
      )}

      {!loading && filtered.length === 0 && (
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          className="text-center py-20"
        >
          <Gamepad2 size={48} className="mx-auto text-dark-border mb-4" />
          <p className="text-muted font-medium">Tidak ada produk ditemukan</p>
          <p className="text-xs text-muted mt-1">Coba kata kunci lain atau ganti kategori</p>
        </motion.div>
      )}
    </section>
  );
}
