import { notFound } from "next/navigation";
import { prisma } from "@/lib/prisma";
import Link from "next/link";
import { BookOpen, Clock, Users, Play, ArrowLeft, ChevronRight } from "lucide-react";
import { getDifficultyColor, getDifficultyLabel } from "@/lib/utils";
import type { Metadata } from "next";

interface Props {
  params: { slug: string };
}

async function getQuiz(slug: string) {
  return prisma.quiz.findUnique({
    where: { slug, isPublished: true },
    include: {
      author: { select: { name: true, image: true, username: true } },
      category: true,
      tags: { include: { tag: true } },
      _count: { select: { questions: true, results: true } },
    },
  });
}

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const quiz = await getQuiz(params.slug);
  if (!quiz) return { title: "Quiz tidak ditemukan" };
  return {
    title: quiz.title,
    description: quiz.description ?? `Quiz ${quiz.title} di QuizB`,
  };
}

export default async function QuizDetailPage({ params }: Props) {
  const quiz = await getQuiz(params.slug);
  if (!quiz) notFound();

  const difficultyColor = getDifficultyColor(quiz.difficulty);
  const difficultyLabel = getDifficultyLabel(quiz.difficulty);

  return (
    <div className="min-h-screen pt-20">
      <div className="container mx-auto px-4 py-8 max-w-2xl">
        {/* Back */}
        <Link
          href="/explore"
          className="inline-flex items-center gap-2 text-sm text-muted-foreground hover:text-foreground transition-colors mb-6"
        >
          <ArrowLeft className="w-4 h-4" />
          Kembali ke Explore
        </Link>

        {/* Quiz Card */}
        <div className="bg-card border border-border rounded-3xl overflow-hidden shadow-xl">
          {/* Thumbnail / Header */}
          <div className="relative h-48 bg-gradient-to-br from-indigo-500/20 to-violet-600/20 flex items-center justify-center">
            <span className="text-8xl opacity-60">{quiz.category.icon ?? "📝"}</span>
            <div className="absolute top-4 left-4">
              <span className="px-3 py-1.5 rounded-full text-xs font-semibold"
                style={{ background: `${quiz.category.color ?? "#6366f1"}cc`, color: "white" }}>
                {quiz.category.icon} {quiz.category.name}
              </span>
            </div>
            <div className="absolute top-4 right-4">
              <span className={`px-3 py-1.5 rounded-full text-xs font-bold bg-card/90 ${difficultyColor}`}>
                {difficultyLabel}
              </span>
            </div>
          </div>

          {/* Info */}
          <div className="p-6">
            <h1 className="text-2xl font-bold mb-2">{quiz.title}</h1>
            {quiz.description && (
              <p className="text-muted-foreground text-sm leading-relaxed mb-6">{quiz.description}</p>
            )}

            {/* Stats */}
            <div className="grid grid-cols-3 gap-3 mb-6">
              {[
                { icon: BookOpen, label: "Jumlah Soal", value: quiz._count.questions },
                { icon: Clock, label: "Per Soal", value: `${quiz.timeLimit}dtk` },
                { icon: Users, label: "Dimainkan", value: quiz.playCount.toLocaleString("id-ID") },
              ].map((s) => {
                const Icon = s.icon;
                return (
                  <div key={s.label} className="bg-muted/50 rounded-2xl p-4 text-center">
                    <Icon className="w-5 h-5 text-primary mx-auto mb-2" />
                    <div className="font-bold text-sm">{s.value}</div>
                    <div className="text-[11px] text-muted-foreground">{s.label}</div>
                  </div>
                );
              })}
            </div>

            {/* Tags */}
            {quiz.tags.length > 0 && (
              <div className="flex flex-wrap gap-2 mb-6">
                {quiz.tags.map(({ tag }) => (
                  <span key={tag.id} className="px-3 py-1 bg-primary/10 text-primary text-xs font-medium rounded-full">
                    #{tag.name}
                  </span>
                ))}
              </div>
            )}

            {/* Author */}
            <div className="flex items-center gap-3 mb-8 p-4 bg-muted/30 rounded-2xl">
              <div className="w-10 h-10 gradient-brand rounded-xl flex items-center justify-center text-white font-bold text-sm">
                {quiz.author.name?.[0] ?? "Q"}
              </div>
              <div>
                <p className="font-semibold text-sm">{quiz.author.name ?? "QuizB Team"}</p>
                <p className="text-xs text-muted-foreground">Pembuat Quiz</p>
              </div>
            </div>

            {/* CTA */}
            <div className="flex flex-col gap-3">
              <Link
                href={`/quiz/${quiz.slug}/play`}
                className="flex items-center justify-center gap-2 py-4 gradient-brand text-white font-bold text-lg rounded-2xl hover:opacity-90 transition-opacity shadow-lg shadow-indigo-500/25"
              >
                <Play className="w-5 h-5" fill="white" />
                Mulai Quiz
              </Link>
              {quiz.isGuestAllowed && (
                <Link
                  href={`/quiz/${quiz.slug}/play?guest=true`}
                  className="flex items-center justify-center gap-2 py-3 border border-border rounded-2xl text-sm font-medium hover:bg-accent transition-colors"
                >
                  Coba Tanpa Login
                  <ChevronRight className="w-4 h-4" />
                </Link>
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
