import { useEffect, useState } from "react";
import { addXP, updateStreak, saveHighscore, checkAchievements } from "../utils/gamification";
import Confetti from "../components/Confetti";

export default function ResultPage({
  score,
  total,
  wrongQuestions,
  timeInSeconds,
  mode,
  isRepeatRun,
  onRestart,
  onRepeatWrong,
  onBack,
}) {
  const [xpGained, setXpGained] = useState(0);
  const [newAchievements, setNewAchievements] = useState([]);
  const [isPersonalBest, setIsPersonalBest] = useState(false);
  const [showConfetti, setShowConfetti] = useState(false);

  useEffect(() => {
    const processed = sessionStorage.getItem("quiz_processed") === "true";
    if (processed) {
      // Wenn bereits verarbeitet, berechne nur geschätzte XP für die Anzeige
      let estXp = score * 10;
      if (total >= 30 && !isRepeatRun) {
        estXp += 100;
        if (score === total) estXp += 250;
      }
      setXpGained(estXp);
      return;
    }

    // 1. Streak aktualisieren
    updateStreak();

    // 2. Highscore speichern (nur wenn kein reines Wiederholungstraining)
    let personalBest = false;
    if (!isRepeatRun) {
      const hsRes = saveHighscore(score, total, timeInSeconds, mode);
      personalBest = hsRes.isNewPersonalBest;
      setIsPersonalBest(personalBest);
    }

    // 3. XP berechnen
    let baseXp = score * 10;
    let completionBonus = 0;
    let perfectBonus = 0;

    if (total >= 30 && !isRepeatRun) {
      completionBonus = 100;
      if (score === total) {
        perfectBonus = 250;
      }
    }

    const initialGained = baseXp + completionBonus + perfectBonus;
    addXP(initialGained);

    // 4. Achievements checken
    const unlocked = checkAchievements({
      score,
      total,
      timeInSeconds,
      mode,
      isRepeatRun
    });

    setNewAchievements(unlocked.map((u) => u.achievement));

    const totalXpGained = initialGained + unlocked.reduce((sum, u) => sum + u.achievement.xpBonus, 0);
    setXpGained(totalXpGained);

    if (score === total || unlocked.length > 0) {
      setShowConfetti(true);
    }

    sessionStorage.setItem("quiz_processed", "true");
  }, [score, total, timeInSeconds, mode, isRepeatRun]);

  const percentage = Math.round((score / total) * 100);

  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 flex flex-col items-center justify-center bg-gray-50 dark:bg-gray-900 text-gray-900 dark:text-gray-100 py-10 px-4">
      {showConfetti && <Confetti />}

      <div className="bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 p-8 rounded-3xl shadow-xl border border-gray-100 dark:border-gray-700 max-w-lg w-full text-center space-y-6 transform transition-all duration-500 scale-100 animate-float-in">
        
        {/* Titel und Trophäe */}
        <header className="space-y-2">
          {score === total ? (
            <span className="text-6xl animate-bounce inline-block">🏆</span>
          ) : percentage >= 80 ? (
            <span className="text-6xl inline-block">🥈</span>
          ) : (
            <span className="text-6xl inline-block">📝</span>
          )}
          <h1 className="text-3xl font-black bg-gradient-to-r from-blue-600 to-indigo-500 dark:from-blue-400 dark:to-indigo-300 bg-clip-text text-transparent">
            {score === total ? "Hervorragend!" : percentage >= 80 ? "Bestanden!" : "Gelernt!"}
          </h1>
          <p className="text-xs uppercase tracking-wider text-gray-400 dark:text-gray-500 font-bold">
            {isRepeatRun ? "Wiederholungs-Modus" : `Modus: ${mode.toUpperCase()}-Lizenz`}
          </p>
        </header>

        {/* Ergebnisse & Progress Ring */}
        <section className="relative flex flex-col items-center py-4">
          <div className="relative w-32 h-32 flex items-center justify-center rounded-full border-8 border-gray-100 dark:border-gray-700 shadow-inner">
            <div
              className={`absolute inset-0 rounded-full border-8 border-transparent transition-all duration-1000`}
              style={{
                borderTopColor: percentage >= 80 ? "#10b981" : "#3b82f6",
                borderRightColor: percentage >= 90 ? "#10b981" : "transparent",
                transform: `rotate(${Math.min(360, (percentage / 100) * 360)}deg)`
              }}
            />
            <div className="text-center">
              <span className="text-3xl font-black">{percentage}%</span>
              <p className="text-[10px] text-gray-400 dark:text-gray-500 font-bold uppercase tracking-wide">Richtig</p>
            </div>
          </div>
          
          <p className="text-lg font-bold mt-4">
            Du hast <span className="text-blue-600 dark:text-blue-400">{score}</span> von <span className="font-extrabold">{total}</span> Fragen richtig beantwortet.
          </p>
        </section>

        {/* Gamification Stats Card */}
        <section className="bg-gray-50 dark:bg-gray-900/50 rounded-2xl p-4 border border-gray-100 dark:border-gray-800 grid grid-cols-2 gap-4 text-left">
          <div>
            <p className="text-xs text-gray-400 dark:text-gray-500 font-medium">⚡ Belohnung</p>
            <p className="text-lg font-black text-emerald-600 dark:text-emerald-400">
              +{xpGained} XP
            </p>
          </div>
          <div>
            <p className="text-xs text-gray-400 dark:text-gray-500 font-medium">⏱️ Zeit</p>
            <p className="text-lg font-black">{formatTime(timeInSeconds)}</p>
          </div>
          {isPersonalBest && (
            <div className="col-span-2 bg-yellow-50 dark:bg-yellow-950/20 border border-yellow-200 dark:border-yellow-900/40 rounded-xl p-2 flex items-center justify-center gap-2 text-yellow-700 dark:text-yellow-400 text-xs font-bold animate-pulse">
              <span>👑</span> Neue persönliche Bestleistung!
            </div>
          )}
        </section>

        {/* Neue Achievements */}
        {newAchievements.length > 0 && (
          <section className="space-y-2 text-left">
            <h2 className="text-xs font-bold text-gray-400 uppercase tracking-wider">Erfolge freigeschaltet! 🎉</h2>
            <div className="space-y-2">
              {newAchievements.map((ach) => (
                <div
                  key={ach.id}
                  className="flex items-center gap-3 p-3 bg-gradient-to-r from-amber-50 to-orange-50/50 dark:from-amber-950/20 dark:to-orange-950/10 border border-amber-200 dark:border-amber-900/40 rounded-xl animate-pulse"
                >
                  <span className="text-2xl">{ach.title.split(" ").slice(-1)[0]}</span>
                  <div className="flex-1">
                    <p className="text-xs font-black text-amber-800 dark:text-amber-300">
                      {ach.title.split(" ").slice(0, -1).join(" ")}
                    </p>
                    <p className="text-[10px] text-gray-500 dark:text-gray-400">{ach.description}</p>
                  </div>
                  <span className="text-xs font-black text-amber-700 dark:text-amber-400">
                    +{ach.xpBonus} XP
                  </span>
                </div>
              ))}
            </div>
          </section>
        )}

        {/* Falsche Fragen & Navigation */}
        <section className="space-y-3 pt-2">
          {wrongQuestions.length > 0 ? (
            <div className="flex flex-col gap-3">
              <button
                onClick={onRepeatWrong}
                className="w-full bg-amber-500 hover:bg-amber-600 text-white font-bold py-3 px-6 rounded-xl transition duration-300 shadow-md hover:shadow-lg cursor-pointer transform hover:-translate-y-0.5"
              >
                Falsche Fragen wiederholen ({wrongQuestions.length})
              </button>
              <button
                onClick={onRestart}
                className="w-full bg-blue-600 hover:bg-blue-700 text-white font-bold py-3 px-6 rounded-xl transition duration-300 shadow-md hover:shadow-lg cursor-pointer transform hover:-translate-y-0.5"
              >
                Neues Quiz starten (30 Fragen)
              </button>
            </div>
          ) : (
            <div className="space-y-3">
              <p className="text-xs font-bold text-emerald-600 dark:text-emerald-400 bg-emerald-50 dark:bg-emerald-950/20 py-2.5 px-4 rounded-xl border border-emerald-200 dark:border-emerald-900/30">
                Perfekt! Du hast alle Fragen richtig beantwortet! 🥳
              </p>
              <button
                onClick={onRestart}
                className="w-full bg-blue-600 hover:bg-blue-700 text-white font-bold py-3 px-6 rounded-xl transition duration-300 shadow-md hover:shadow-lg cursor-pointer transform hover:-translate-y-0.5"
              >
                Erneut testen (neue Fragen)
              </button>
            </div>
          )}

          <button
            onClick={onBack}
            className="text-xs font-semibold text-gray-500 dark:text-gray-400 hover:text-blue-600 dark:hover:text-blue-400 hover:underline transition cursor-pointer mt-2 block mx-auto"
          >
            Zurück zur Startseite
          </button>
        </section>

      </div>
    </div>
  );
}
