"use client";

import { motion } from "framer-motion";
import Link from "next/link";
import Image from "next/image";
import {
  Trophy, Zap, Target, TrendingUp, BookOpen, Flame,
  ChevronRight, Clock, Play, ArrowRight,
} from "lucide-react";
import { cn, formatTime, getInitials } from "@/lib/utils";

interface BentoDashboardProps {
  stats: {
    user: {
      name?: string | null;
      image?: string | null;
      level: number;
      xp: number;
      streak: number;
      totalScore: number;
      quizzesPlayed: number;
    } | null;
    recentResults: {
      id: string;
      score: number;
      percentage: number;
      timeTaken: number;
      quiz: {
        title: string;
        slug: string;
        category: { name: string; icon?: string | null } | null;
      } | null;
    }[];
    totalResults: number;
    avgScore: number;
  };
  user: {
    name?: string | null;
    email?: string | null;
    image?: string | null;
  };
}

const containerVariants = {
  hidden: {},
  visible: { transition: { staggerChildren: 0.08 } },
};

const itemVariants = {
  hidden: { opacity: 0, y: 20, scale: 0.97 },
  visible: { opacity: 1, y: 0, scale: 1, transition: { duration: 0.5, ease: "easeOut" as const } },
};

function BentoCard({
  children,
  className,
  href,
}: {
  children: React.ReactNode;
  className?: string;
  href?: string;
}) {
  const card = (
    <motion.div
      variants={itemVariants}
      whileHover={{ y: -3, transition: { duration: 0.2 } }}
      className={cn(
        "bg-card border border-border rounded-2xl p-5 overflow-hidden relative group",
        "hover:border-primary/30 hover:shadow-xl hover:shadow-primary/5 transition-colors",
        className
      )}
    >
      {children}
    </motion.div>
  );

  if (href) {
    return <Link href={href}>{card}</Link>;
  }
  return card;
}

export function BentoDashboard({ stats, user }: BentoDashboardProps) {
  const { recentResults, totalResults, avgScore } = stats;
  const dbUser = stats.user;

  const XP_PER_LEVEL = 500;
  const xpProgress = dbUser ? ((dbUser.xp % XP_PER_LEVEL) / XP_PER_LEVEL) * 100 : 0;

  return (
    <div>
      {/* Page Header */}
      <motion.div
        initial={{ opacity: 0, y: -10 }}
        animate={{ opacity: 1, y: 0 }}
        className="mb-8"
      >
        <h1 className="text-3xl font-bold">
          Selamat datang, {user?.name?.split(" ")[0] ?? "Kamu"}! 👋
        </h1>
        <p className="text-muted-foreground mt-1">
          Pantau perkembangan belajarmu hari ini.
        </p>
      </motion.div>

      {/* Bento Grid */}
      <motion.div
        variants={containerVariants}
        initial="hidden"
        animate="visible"
        className="grid grid-cols-2 md:grid-cols-4 gap-4 auto-rows-auto"
      >

        {/* 1. Profile Card — spans 2 cols, 2 rows */}
        <BentoCard className="col-span-2 row-span-2">
          <div className="flex flex-col h-full">
            <div className="flex items-start gap-4 mb-6">
              <div className="relative">
                {user?.image ? (
                  <Image src={user.image} alt={user.name ?? ""} width={64} height={64} className="rounded-2xl" />
                ) : (
                  <div className="w-16 h-16 gradient-brand rounded-2xl flex items-center justify-center text-white text-xl font-bold">
                    {getInitials(user?.name ?? "U")}
                  </div>
                )}
                <div className="absolute -bottom-1 -right-1 w-6 h-6 bg-emerald-500 rounded-full flex items-center justify-center">
                  <span className="text-[9px] text-white font-bold">
                    {dbUser?.level ?? 1}
                  </span>
                </div>
              </div>
              <div className="flex-1 min-w-0">
                <h2 className="font-bold text-lg truncate">{user?.name ?? "Pengguna"}</h2>
                <p className="text-sm text-muted-foreground">{user?.email}</p>
                <div className="flex items-center gap-1.5 mt-1">
                  <Zap className="w-3.5 h-3.5 text-violet-500" />
                  <span className="text-sm font-semibold text-violet-500">
                    Level {dbUser?.level ?? 1}
                  </span>
                </div>
              </div>
            </div>

            {/* XP Progress */}
            <div className="mb-6">
              <div className="flex justify-between items-center mb-2">
                <span className="text-sm font-medium">Progress XP</span>
                <span className="text-xs text-muted-foreground">
                  {(dbUser?.xp ?? 0) % XP_PER_LEVEL} / {XP_PER_LEVEL} XP
                </span>
              </div>
              <div className="h-3 bg-muted rounded-full overflow-hidden">
                <motion.div
                  className="h-full gradient-brand rounded-full"
                  initial={{ width: 0 }}
                  animate={{ width: `${xpProgress}%` }}
                  transition={{ duration: 1, delay: 0.5, ease: "easeOut" }}
                />
              </div>
            </div>

            {/* Quick stats row */}
            <div className="grid grid-cols-3 gap-3 mt-auto">
              {[
                { label: "Quiz", value: totalResults, icon: BookOpen, color: "text-indigo-500" },
                { label: "Skor", value: `${avgScore}%`, icon: Target, color: "text-emerald-500" },
                { label: "Streak", value: `${dbUser?.streak ?? 0}🔥`, icon: Flame, color: "text-orange-500" },
              ].map((s) => {
                const Icon = s.icon;
                return (
                  <div key={s.label} className="bg-muted/50 rounded-xl p-3 text-center">
                    <Icon className={`w-4 h-4 ${s.color} mx-auto mb-1`} />
                    <div className="font-bold text-sm">{s.value}</div>
                    <div className="text-[10px] text-muted-foreground">{s.label}</div>
                  </div>
                );
              })}
            </div>
          </div>
        </BentoCard>

        {/* 2. Total Score */}
        <BentoCard className="col-span-1">
          <div className="flex flex-col h-full">
            <Trophy className="w-8 h-8 text-yellow-500 mb-3" />
            <div className="text-3xl font-black gradient-text">
              {(dbUser?.totalScore ?? 0).toLocaleString("id-ID")}
            </div>
            <p className="text-xs text-muted-foreground mt-1 font-medium">Total Poin</p>
          </div>
        </BentoCard>

        {/* 3. Avg Score */}
        <BentoCard className="col-span-1">
          <div className="flex flex-col h-full">
            <TrendingUp className="w-8 h-8 text-emerald-500 mb-3" />
            <div className="text-3xl font-black text-emerald-500">{avgScore}%</div>
            <p className="text-xs text-muted-foreground mt-1 font-medium">Rata-rata Skor</p>
          </div>
        </BentoCard>

        {/* 4. Start Quiz CTA — gradient */}
        <BentoCard className="col-span-2 gradient-brand text-white border-0" href="/explore">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-white/80 text-sm font-medium mb-1">Siap belajar?</p>
              <h3 className="text-xl font-bold">Mulai Quiz Baru</h3>
            </div>
            <div className="w-12 h-12 bg-white/20 rounded-2xl flex items-center justify-center group-hover:scale-110 transition-transform">
              <Play className="w-6 h-6 text-white" fill="white" />
            </div>
          </div>
          <div className="mt-4 flex items-center gap-1 text-sm text-white/80 font-medium">
            Jelajahi quiz <ArrowRight className="w-4 h-4" />
          </div>
        </BentoCard>

        {/* 5. Recent Activity — spans full width */}
        <BentoCard className="col-span-2 md:col-span-4">
          <div className="flex items-center justify-between mb-4">
            <h3 className="font-bold text-base">Aktivitas Terbaru</h3>
            <Link
              href="/dashboard/history"
              className="flex items-center gap-1 text-xs font-semibold text-primary hover:underline"
            >
              Lihat Semua <ChevronRight className="w-3 h-3" />
            </Link>
          </div>

          {recentResults.length === 0 ? (
            <div className="text-center py-8 text-muted-foreground">
              <BookOpen className="w-10 h-10 mx-auto mb-3 opacity-30" />
              <p className="text-sm">Belum ada quiz yang dimainkan.</p>
              <Link href="/explore" className="text-sm text-primary font-semibold hover:underline mt-1 inline-block">
                Mulai sekarang →
              </Link>
            </div>
          ) : (
            <div className="space-y-2">
              {recentResults.map((result, i) => (
                <motion.div
                  key={result.id}
                  initial={{ opacity: 0, x: -10 }}
                  animate={{ opacity: 1, x: 0 }}
                  transition={{ delay: i * 0.07 }}
                  className="flex items-center gap-3 p-3 rounded-xl hover:bg-accent transition-colors"
                >
                  <div className="w-9 h-9 rounded-xl bg-primary/10 flex items-center justify-center text-lg flex-shrink-0">
                    {result.quiz?.category?.icon ?? "📝"}
                  </div>
                  <div className="flex-1 min-w-0">
                    <p className="font-semibold text-sm truncate">{result.quiz?.title}</p>
                    <div className="flex items-center gap-3 text-xs text-muted-foreground">
                      <span className="flex items-center gap-1">
                        <Clock className="w-3 h-3" />
                        {formatTime(result.timeTaken)}
                      </span>
                    </div>
                  </div>
                  <div className="text-right flex-shrink-0">
                    <div className={cn(
                      "text-lg font-black",
                      result.percentage >= 80 ? "text-emerald-500" :
                      result.percentage >= 60 ? "text-amber-500" : "text-rose-500"
                    )}>
                      {Math.round(result.percentage)}%
                    </div>
                    <div className="text-xs text-muted-foreground">{result.score} poin</div>
                  </div>
                </motion.div>
              ))}
            </div>
          )}
        </BentoCard>

      </motion.div>
    </div>
  );
}
