"use client";

import { useState, useEffect } from "react";
import { motion } from "framer-motion";
import Navbar from "@/components/layout/Navbar";
import Footer from "@/components/layout/Footer";
import MobileNav from "@/components/layout/MobileNav";
import { Trophy, Crown, Medal, Flame } from "lucide-react";

const TABS = [
  { key: "today", label: "Hari Ini" },
  { key: "yesterday", label: "Kemarin" },
  { key: "week", label: "Minggu Ini" },
  { key: "month", label: "Bulan Ini" },
  { key: "all", label: "All Time" },
];

function censor(text: string) {
  if (!text) return "***";
  if (text.includes("@")) {
    const [name, domain] = text.split("@");
    return name.slice(0, 3) + "***@" + domain.slice(0, 2) + "***";
  }
  if (text.length <= 4) return text.slice(0, 2) + "***";
  return text.slice(0, 4) + "***" + text.slice(-2);
}

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

// Data fetching will be done in the component

const RANK_ICONS = [
  <Crown key="1" size={20} className="text-yellow-400" />,
  <Medal key="2" size={20} className="text-gray-300" />,
  <Medal key="3" size={20} className="text-amber-600" />,
];

export default function LeaderboardPage() {
  const [activeTab, setActiveTab] = useState("all");
  const [data, setData] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    setLoading(true);
    const apiUrl = process.env.NEXT_PUBLIC_API_URL ;
    fetch(`${apiUrl}/api/v2/leaderboard?period=${activeTab}`)
      .then((res) => res.json())
      .then((res) => {
        if (res.success && res.data) {
          setData(res.data);
        } else {
          setData([]);
        }
      })
      .catch((err) => {
        console.error('Failed to load leaderboard', err);
        setData([]);
      })
      .finally(() => {
        setLoading(false);
      });
  }, [activeTab]);

  return (
    <>
      <Navbar />
      <main className="max-w-5xl mx-auto px-4 pt-24 pb-24 lg:pb-12">
        {/* Header */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          className="text-center mb-8"
        >
          <div className="inline-flex items-center gap-2 px-4 py-2 rounded-full bg-secondary/10 border border-secondary/20 mb-4">
            <Trophy size={16} className="text-secondary" />
            <span className="text-xs font-semibold text-secondary">Top Spenders</span>
          </div>
          <h1 className="font-heading text-3xl md:text-4xl font-black text-white">
            Leader<span className="gradient-text">board</span>
          </h1>
          <p className="text-sm text-muted mt-2">Top customer {process.env.NEXT_PUBLIC_APP_NAME} berdasarkan total transaksi</p>
        </motion.div>

        {/* Period Tabs */}
        <div className="flex justify-center gap-2 flex-wrap mb-8">
          {TABS.map((tab) => (
            <button
              key={tab.key}
              onClick={() => setActiveTab(tab.key)}
              className={`px-4 py-2 rounded-xl text-xs font-semibold transition-all duration-300 ${
                activeTab === tab.key
                  ? "bg-primary text-white shadow-glow-sm"
                  : "bg-dark-surface text-muted border border-dark-border hover:border-primary/30"
              }`}
            >
              {tab.label}
            </button>
          ))}
        </div>

        {/* Top 3 podium */}
        {!loading && data.length > 0 && (
          <div className="grid grid-cols-3 gap-3 mb-8 max-w-lg mx-auto items-end h-56">
            {data.slice(0, 3).map((user, i) => {
              const order = [1, 0, 2]; // Center = #1
              const idx = order[i];
              const u = data[idx];
              if (!u) return <div key={`empty-${i}`} className="w-full" />;

              const heights = ["h-32", "h-40", "h-28"];
              const bgGradients = [
                "from-gray-500/20 to-gray-600/10",
                "from-yellow-500/20 to-orange-500/10",
                "from-amber-700/20 to-amber-800/10",
              ];

              return (
                <motion.div
                  key={idx}
                  initial={{ opacity: 0, y: 30 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ delay: i * 0.15 }}
                  className="flex flex-col items-center justify-end h-full"
                >
                  <div className="w-12 h-12 rounded-full bg-dark-surface2 border-2 border-dark-border flex items-center justify-center mb-2 text-lg">
                    {["🥈", "🥇", "🥉"][i]}
                  </div>
                  <p className="text-xs font-bold text-white truncate max-w-full mb-1">{censor(u.username)}</p>
                  <p className="text-[10px] text-primary font-semibold mb-2">{formatRp(u.total)}</p>
                  <div className={`w-full ${heights[i]} rounded-t-xl bg-gradient-to-t ${bgGradients[i]} border border-dark-border border-b-0 flex items-end justify-center pb-2 mt-auto`}>
                    <span className="text-2xl font-heading font-black text-white/50">#{idx + 1}</span>
                  </div>
                </motion.div>
              );
            })}
          </div>
        )}

        {/* Full leaderboard table */}
        <div className="glass rounded-2xl overflow-hidden">
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead>
                <tr className="border-b border-dark-border">
                  <th className="px-4 py-3 text-left text-xs font-semibold text-muted uppercase tracking-wider">Rank</th>
                  <th className="px-4 py-3 text-left text-xs font-semibold text-muted uppercase tracking-wider">User</th>
                  <th className="px-4 py-3 text-left text-xs font-semibold text-muted uppercase tracking-wider hidden sm:table-cell">Game Favorit</th>
                  <th className="px-4 py-3 text-right text-xs font-semibold text-muted uppercase tracking-wider">Orders</th>
                  <th className="px-4 py-3 text-right text-xs font-semibold text-muted uppercase tracking-wider">Total</th>
                </tr>
              </thead>
              <tbody>
                {loading ? (
                  <tr>
                    <td colSpan={5} className="px-4 py-8 text-center text-sm text-muted">
                      Memuat data...
                    </td>
                  </tr>
                ) : data.length === 0 ? (
                  <tr>
                    <td colSpan={5} className="px-4 py-8 text-center text-sm text-muted">
                      Belum ada data transaksi di periode ini.
                    </td>
                  </tr>
                ) : (
                  data.map((user, i) => (
                    <motion.tr
                      key={i}
                      initial={{ opacity: 0, x: -10 }}
                      animate={{ opacity: 1, x: 0 }}
                      transition={{ delay: i * 0.05 }}
                      className={`border-b border-dark-border/50 hover:bg-white/[0.02] transition-colors ${
                        i < 3 ? "bg-primary/[0.03]" : ""
                      }`}
                    >
                      <td className="px-4 py-3">
                        <div className="flex items-center gap-2">
                          {i < 3 ? RANK_ICONS[i] : (
                            <span className="text-sm font-bold text-muted w-5 text-center">{i + 1}</span>
                          )}
                        </div>
                      </td>
                      <td className="px-4 py-3">
                        <p className="text-sm font-semibold text-white">{censor(user.username)}</p>
                        <p className="text-[10px] text-muted">{censor(user.email)}</p>
                      </td>
                      <td className="px-4 py-3 hidden sm:table-cell">
                        <span className="text-xs text-muted">{user.topGame}</span>
                      </td>
                      <td className="px-4 py-3 text-right">
                        <span className="text-xs font-semibold text-white">{user.orders}x</span>
                      </td>
                      <td className="px-4 py-3 text-right">
                        <span className="text-sm font-bold text-primary">{formatRp(user.total)}</span>
                      </td>
                    </motion.tr>
                  ))
                )}
              </tbody>
            </table>
          </div>
        </div>

        {/* Info */}
        <div className="mt-6 text-center">
          <div className="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-dark-surface border border-dark-border text-[10px] text-muted">
            <Flame size={12} className="text-primary" />
            Data diperbarui secara realtime. Belanja lebih banyak untuk naik peringkat!
          </div>
        </div>
      </main>
      <Footer />
      <MobileNav />
    </>
  );
}
