import { useEffect, useState } from "react";
import {
  getXP,
  getLevelProgress,
  getStreak,
  getUnlockedAchievements,
  getHighscores,
  ACHIEVEMENTS_LIST
} from "../utils/gamification";

export default function ModeSelectPage({ onSelect }) {
  const [xp, setXp] = useState(0);
  const [streak, setStreak] = useState(0);
  const [unlocked, setUnlocked] = useState([]);
  const [highscores, setHighscores] = useState([]);
  const [activeTab, setActiveTab] = useState("achievements"); // "achievements" | "highscores"

  useEffect(() => {
    setXp(getXP());
    setStreak(getStreak());
    setUnlocked(getUnlockedAchievements());
    setHighscores(getHighscores());
  }, []);

  const progress = getLevelProgress(xp);

  const formatTime = (secs) => {
    const m = Math.floor(secs / 60);
    const s = secs % 60;
    return `${m}:${s < 10 ? "0" : ""}${s}`;
  };

  return (
    <div className="min-h-screen bg-gray-50 dark:bg-gray-900 text-gray-900 dark:text-gray-100 py-8 px-4 sm:px-6">
      <div className="max-w-5xl mx-auto space-y-6">

        {/* Header mit Titel und Streak */}
        <header className="flex flex-col sm:flex-row justify-between items-center bg-white dark:bg-gray-800 p-6 rounded-2xl shadow-sm border border-gray-100 dark:border-gray-700 gap-4 transition-all">
          <div className="text-center sm:text-left">
            <h1 className="text-3xl font-extrabold bg-gradient-to-r from-blue-600 to-indigo-500 dark:from-blue-400 dark:to-indigo-300 bg-clip-text text-transparent">
              Schiri-Trainer Volleyball
            </h1>
          </div>

          {/* Streak Flame */}
          <div className="flex items-center gap-3 px-4 py-2 bg-amber-50 dark:bg-amber-950/30 border border-amber-200 dark:border-amber-900/50 rounded-full shadow-inner animate-pulse">
            <span className="text-2xl">🔥</span>
            <div className="text-left">
              <p className="text-xs text-amber-600 dark:text-amber-400 font-semibold uppercase tracking-wider">Lernserie</p>
              <p className="text-lg font-bold text-amber-800 dark:text-amber-300">
                {streak} {streak === 1 ? "Tag" : "Tage"}
              </p>
            </div>
          </div>
        </header>

        {/* Dashboard Grid */}
        <div className="grid grid-cols-1 md:grid-cols-3 gap-6">

          {/* LINKE SPALTE: Profil, Modusauswahl */}
          <div className="md:col-span-2 space-y-6">

            {/* Level & XP Card */}
            <section className="bg-white dark:bg-gray-800 p-6 rounded-2xl shadow-sm border border-gray-100 dark:border-gray-700">
              <div className="flex justify-between items-center mb-3">
                <div>
                  <h2 className="text-sm font-bold text-gray-400 dark:text-gray-500 uppercase tracking-wider">Erfahrungsstufe</h2>
                  <p className="text-3xl font-black text-blue-600 dark:text-blue-400">Level {progress.currentLevel}</p>
                </div>
                <div className="text-right">
                  <p className="text-xs text-gray-400 dark:text-gray-500">Gesamt-XP</p>
                  <p className="text-lg font-extrabold">{xp} XP</p>
                </div>
              </div>

              {/* Progress Bar */}
              <div className="space-y-1">
                <div className="w-full bg-gray-100 dark:bg-gray-700 h-4 rounded-full overflow-hidden p-[2px] border border-gray-200/50 dark:border-gray-600/50">
                  <div
                    className="h-full bg-gradient-to-r from-blue-500 to-indigo-500 dark:from-blue-600 dark:to-indigo-500 rounded-full transition-all duration-1000 ease-out"
                    style={{ width: `${progress.percentage}%` }}
                  />
                </div>
                <div className="flex justify-between text-xs text-gray-500 dark:text-gray-400 font-medium">
                  <span>{progress.xpCurrentLevelStart} XP</span>
                  <span>{progress.percentage}% zum nächsten Level</span>
                  <span>{progress.xpNextLevelStart} XP</span>
                </div>
              </div>
            </section>

            {/* Modusauswahl Card */}
            <section className="bg-white dark:bg-gray-800 p-6 rounded-2xl shadow-sm border border-gray-100 dark:border-gray-700">
              <h2 className="text-xl font-bold mb-4">Starte ein neues Quiz</h2>
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">

                {/* D-Lizenz */}
                <button
                  onClick={() => onSelect("d")}
                  className="group relative flex flex-col items-center justify-center p-6 bg-gradient-to-br from-blue-50 to-blue-100/30 dark:from-blue-950/20 dark:to-blue-900/10 border border-blue-200/60 dark:border-blue-800/40 rounded-2xl shadow-sm hover:shadow-md hover:border-blue-400 dark:hover:border-blue-600 text-center transition-all duration-300 transform hover:-translate-y-1 cursor-pointer"
                >
                  <span className="text-4xl mb-3 group-hover:scale-110 transition-transform">🥉</span>
                  <h3 className="text-lg font-bold text-blue-900 dark:text-blue-300">D-Lizenz</h3>
                  <p className="text-xs text-blue-700/70 dark:text-blue-400/70 mt-1 max-w-[200px]">
                    Grundlegende Spielregeln und Standard-Schiedsrichterentscheidungen.
                  </p>
                  <span className="mt-4 px-4 py-1.5 bg-blue-600 group-hover:bg-blue-700 text-white font-semibold text-xs rounded-full shadow-sm group-hover:shadow transition-all">
                    Jetzt lernen
                  </span>
                </button>

                {/* C-Lizenz */}
                <button
                  onClick={() => onSelect("c")}
                  className="group relative flex flex-col items-center justify-center p-6 bg-gradient-to-br from-emerald-50 to-emerald-100/30 dark:from-emerald-950/20 dark:to-emerald-900/10 border border-emerald-200/60 dark:border-emerald-800/40 rounded-2xl shadow-sm hover:shadow-md hover:border-emerald-400 dark:hover:border-emerald-600 text-center transition-all duration-300 transform hover:-translate-y-1 cursor-pointer"
                >
                  <span className="text-4xl mb-3 group-hover:scale-110 transition-transform">🥈</span>
                  <h3 className="text-lg font-bold text-emerald-900 dark:text-emerald-300">C-Lizenz</h3>
                  <p className="text-xs text-emerald-700/70 dark:text-emerald-400/70 mt-1 max-w-[200px]">
                    Fortgeschrittene Regelkunde, Spezialfälle und komplexe Situationen.
                  </p>
                  <span className="mt-4 px-4 py-1.5 bg-emerald-600 group-hover:bg-emerald-700 text-white font-semibold text-xs rounded-full shadow-sm group-hover:shadow transition-all">
                    Jetzt lernen
                  </span>
                </button>

              </div>
            </section>
          </div>

          {/* RECHTE SPALTE: Achievements und Highscores */}
          <div className="space-y-6">

            {/* Tabs Controller */}
            <div className="bg-white dark:bg-gray-800 p-2 rounded-2xl shadow-sm border border-gray-100 dark:border-gray-700 flex gap-2">
              <button
                onClick={() => setActiveTab("achievements")}
                className={`flex-1 py-2 rounded-xl text-sm font-bold transition-all cursor-pointer ${activeTab === "achievements"
                    ? "bg-blue-600 text-white shadow-sm"
                    : "text-gray-500 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-700/50"
                  }`}
              >
                Erfolge
              </button>
              <button
                onClick={() => setActiveTab("highscores")}
                className={`flex-1 py-2 rounded-xl text-sm font-bold transition-all cursor-pointer ${activeTab === "highscores"
                    ? "bg-blue-600 text-white shadow-sm"
                    : "text-gray-500 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-700/50"
                  }`}
              >
                Bestenliste
              </button>
            </div>

            {/* Content Card */}
            <div className="bg-white dark:bg-gray-800 p-6 rounded-2xl shadow-sm border border-gray-100 dark:border-gray-700 min-h-[300px]">

              {/* Tab: Achievements */}
              {activeTab === "achievements" && (
                <div className="space-y-4">
                  <div className="flex justify-between items-center">
                    <h3 className="font-bold text-lg">Erfolge</h3>
                    <span className="text-xs bg-gray-100 dark:bg-gray-700 px-2.5 py-1 rounded-full font-semibold">
                      {unlocked.length} / {ACHIEVEMENTS_LIST.length}
                    </span>
                  </div>

                  <div className="space-y-3 max-h-[350px] overflow-y-auto pr-1">
                    {ACHIEVEMENTS_LIST.map((ach) => {
                      const isUnlocked = unlocked.includes(ach.id);
                      return (
                        <div
                          key={ach.id}
                          className={`flex items-center gap-3 p-3 rounded-xl border transition-all ${isUnlocked
                              ? "bg-blue-50/30 dark:bg-blue-950/10 border-blue-100 dark:border-blue-900/40"
                              : "bg-gray-50/50 dark:bg-gray-800/50 border-gray-100 dark:border-gray-700/30 opacity-60"
                            }`}
                        >
                          <div className={`text-2xl p-1.5 rounded-lg ${isUnlocked ? "bg-white dark:bg-gray-800 shadow-sm" : ""
                            }`}>
                            {ach.title.split(" ").slice(-1)[0]} {/* Nur Emoji */}
                          </div>

                          <div className="flex-1 min-w-0">
                            <p className={`text-sm font-bold truncate ${isUnlocked ? "text-gray-900 dark:text-white" : "text-gray-500 dark:text-gray-400"
                              }`}>
                              {ach.title.split(" ").slice(0, -1).join(" ")}
                            </p>
                            <p className="text-xs text-gray-400 dark:text-gray-500 line-clamp-2 leading-tight">
                              {ach.description}
                            </p>
                          </div>

                          <div className="text-right shrink-0">
                            <span className="text-xs font-bold text-blue-600 dark:text-blue-400 bg-blue-50 dark:bg-blue-950/40 px-2 py-0.5 rounded">
                              +{ach.xpBonus} XP
                            </span>
                          </div>
                        </div>
                      );
                    })}
                  </div>
                </div>
              )}

              {/* Tab: Highscores */}
              {activeTab === "highscores" && (
                <div className="space-y-4">
                  <h3 className="font-bold text-lg">Top 5 Versuche</h3>
                  {highscores.length === 0 ? (
                    <div className="text-center py-12 text-gray-400 dark:text-gray-500">
                      <span className="text-4xl block mb-2">🏆</span>
                      <p className="text-sm">Noch keine Einträge vorhanden.</p>
                      <p className="text-xs">Beende dein erstes Quiz, um hier gelistet zu werden!</p>
                    </div>
                  ) : (
                    <div className="space-y-2">
                      {highscores.map((hs, idx) => (
                        <div
                          key={idx}
                          className="flex items-center justify-between p-3 bg-gray-50 dark:bg-gray-900/50 rounded-xl border border-gray-100 dark:border-gray-800"
                        >
                          <div className="flex items-center gap-3">
                            <span className={`w-6 h-6 flex items-center justify-center font-black rounded-full text-xs ${idx === 0
                                ? "bg-yellow-400 text-yellow-950"
                                : idx === 1
                                  ? "bg-slate-300 text-slate-800"
                                  : idx === 2
                                    ? "bg-amber-600 text-amber-50"
                                    : "bg-gray-200 dark:bg-gray-700 text-gray-600 dark:text-gray-400"
                              }`}>
                              {idx + 1}
                            </span>
                            <div>
                              <div className="flex items-center gap-1.5">
                                <span className="font-bold text-sm">{hs.score}/{hs.total}</span>
                                <span className={`text-[10px] font-bold px-1.5 py-0.2 rounded-full ${hs.mode === "D"
                                    ? "bg-blue-100 dark:bg-blue-900/40 text-blue-600 dark:text-blue-400"
                                    : "bg-emerald-100 dark:bg-emerald-900/40 text-emerald-600 dark:text-emerald-400"
                                  }`}>
                                  {hs.mode}
                                </span>
                              </div>
                              <span className="text-[10px] text-gray-400 dark:text-gray-500">{hs.date}</span>
                            </div>
                          </div>
                          <div className="text-right">
                            <p className="font-extrabold text-sm text-gray-700 dark:text-gray-300">{hs.percentage}%</p>
                            <p className="text-[10px] text-gray-400 dark:text-gray-500">⏱️ {formatTime(hs.time)}</p>
                          </div>
                        </div>
                      ))}
                    </div>
                  )}
                </div>
              )}

            </div>
          </div>

        </div>

      </div>
    </div>
  );
}
