"use client";

import { motion } from "framer-motion";
import Link from "next/link";
import { Share2, RotateCcw, Home, Star, Clock, Target, Zap } from "lucide-react";
import { formatTime, calculateXP } from "@/lib/utils";
import { toast } from "sonner";

interface ResultCardProps {
  quiz: { id: string; title: string; difficulty: string };
  score: number;
  totalPoints: number;
  percentage: number;
  timeTaken: number;
  answers: { isCorrect: boolean }[];
  questions: { id: string; points: number }[];
  isGuest: boolean;
}

function getGrade(percentage: number) {
  if (percentage >= 90) return { grade: "A+", label: "Luar Biasa! 🏆", color: "text-yellow-500" };
  if (percentage >= 80) return { grade: "A", label: "Sangat Bagus! 🌟", color: "text-emerald-500" };
  if (percentage >= 70) return { grade: "B", label: "Bagus! 👍", color: "text-blue-500" };
  if (percentage >= 60) return { grade: "C", label: "Cukup 😊", color: "text-indigo-500" };
  if (percentage >= 50) return { grade: "D", label: "Perlu Belajar Lagi 📚", color: "text-amber-500" };
  return { grade: "E", label: "Jangan Menyerah! 💪", color: "text-rose-500" };
}

export function ResultCard({
  quiz, score, totalPoints, percentage, timeTaken, answers, questions, isGuest,
}: ResultCardProps) {
  const { grade, label, color } = getGrade(percentage);
  const correctCount = answers.filter((a) => a.isCorrect).length;
  const xpGained = calculateXP(score, percentage, quiz.difficulty);

  const handleShare = () => {
    const text = `Saya baru menyelesaikan quiz "${quiz.title}" di QuizB!\n🏆 Skor: ${percentage}% (${grade})\n✅ ${correctCount}/${questions.length} benar\n\nCoba kamu: ${window.location.origin}/quiz/${quiz.id}`;
    if (navigator.share) {
      navigator.share({ title: "QuizB Result", text });
    } else {
      navigator.clipboard.writeText(text);
      toast.success("Hasil disalin ke clipboard!");
    }
  };

  return (
    <div className="min-h-screen flex items-center justify-center p-4">
      <motion.div
        initial={{ opacity: 0, scale: 0.8 }}
        animate={{ opacity: 1, scale: 1 }}
        transition={{ type: "spring", stiffness: 200, damping: 20 }}
        className="w-full max-w-md"
      >
        {/* Main Card */}
        <div className="bg-card border border-border rounded-3xl overflow-hidden shadow-2xl">
          {/* Header */}
          <div className="relative p-8 text-center gradient-brand text-white">
            <div className="absolute inset-0 opacity-20"
              style={{ backgroundImage: "radial-gradient(circle at 50% 0%, rgba(255,255,255,0.4) 0%, transparent 60%)" }}
            />

            <motion.div
              initial={{ scale: 0, rotate: -180 }}
              animate={{ scale: 1, rotate: 0 }}
              transition={{ type: "spring", stiffness: 300, damping: 20, delay: 0.2 }}
              className="w-24 h-24 bg-white/20 backdrop-blur-sm rounded-full flex items-center justify-center mx-auto mb-4 border-4 border-white/30"
            >
              <span className={`text-4xl font-black ${color.replace("text-", "text-white")}`}>
                {percentage}%
              </span>
            </motion.div>

            <motion.div
              initial={{ opacity: 0, y: 10 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: 0.4 }}
            >
              <div className="text-2xl font-black mb-1">{grade}</div>
              <p className="text-white/90 font-medium">{label}</p>
            </motion.div>
          </div>

          {/* Stats Grid */}
          <div className="p-6">
            <div className="grid grid-cols-2 gap-3 mb-6">
              {[
                { icon: Target, label: "Jawaban Benar", value: `${correctCount}/${questions.length}`, color: "text-emerald-500", bg: "bg-emerald-500/10" },
                { icon: Star, label: "Poin", value: `${score}/${totalPoints}`, color: "text-amber-500", bg: "bg-amber-500/10" },
                { icon: Clock, label: "Waktu", value: formatTime(timeTaken), color: "text-blue-500", bg: "bg-blue-500/10" },
                { icon: Zap, label: "XP Didapat", value: `+${xpGained} XP`, color: "text-violet-500", bg: "bg-violet-500/10" },
              ].map((stat, i) => {
                const Icon = stat.icon;
                return (
                  <motion.div
                    key={stat.label}
                    initial={{ opacity: 0, y: 10 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={{ delay: 0.5 + i * 0.1 }}
                    className={`${stat.bg} rounded-2xl p-4`}
                  >
                    <Icon className={`w-5 h-5 ${stat.color} mb-2`} />
                    <div className={`text-lg font-bold ${stat.color}`}>{stat.value}</div>
                    <div className="text-xs text-muted-foreground">{stat.label}</div>
                  </motion.div>
                );
              })}
            </div>

            {/* Guest prompt */}
            {isGuest && (
              <motion.div
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                transition={{ delay: 0.8 }}
                className="mb-4 p-4 bg-primary/10 border border-primary/20 rounded-2xl text-center"
              >
                <p className="text-sm font-medium mb-2">Simpan hasilmu & kumpulkan XP!</p>
                <Link href="/register" className="text-sm font-bold text-primary hover:underline">
                  Daftar Sekarang — Gratis →
                </Link>
              </motion.div>
            )}

            {/* Action Buttons */}
            <motion.div
              initial={{ opacity: 0, y: 10 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: 0.9 }}
              className="flex flex-col gap-3"
            >
              <button
                onClick={handleShare}
                className="flex items-center justify-center gap-2 py-3 bg-primary/10 text-primary font-semibold rounded-xl hover:bg-primary/20 transition-colors"
              >
                <Share2 className="w-4 h-4" />
                Bagikan Hasil
              </button>
              <div className="flex gap-3">
                <Link
                  href={`/quiz/${quiz.id}`}
                  className="flex-1 flex items-center justify-center gap-2 py-3 border border-border rounded-xl font-medium hover:bg-accent transition-colors text-sm"
                >
                  <RotateCcw className="w-4 h-4" />
                  Ulangi
                </Link>
                <Link
                  href="/"
                  className="flex-1 flex items-center justify-center gap-2 py-3 gradient-brand text-white font-semibold rounded-xl text-sm"
                >
                  <Home className="w-4 h-4" />
                  Beranda
                </Link>
              </div>
            </motion.div>
          </div>
        </div>
      </motion.div>
    </div>
  );
}
