"use client";

import { useState, useEffect, useCallback } from "react";
import Link from "next/link";
import { useParams } from "next/navigation";
import { ImportModal } from "@/components/import/ImportModal";

interface QuizItem {
  id: string;
  name: string;
  description: string | null;
  _count: { questions: number; attempts: number };
}

const cache: Record<string, QuizItem[]> = {};

export default function QuizzesPage() {
  const params = useParams();
  const classSlug = params.classSlug as string;
  const [quizzes, setQuizzes] = useState<QuizItem[]>(cache[classSlug] || []);
  const [loading, setLoading] = useState(!cache[classSlug]);
  const [animate] = useState(!cache[classSlug]);
  const [showImport, setShowImport] = useState(false);
  const [classId, setClassId] = useState<string>("");

  const fetchQuizzes = useCallback(async (cId: string) => {
    try {
      const res = await fetch(`/api/quizzes/list?classId=${cId}`);
      if (res.ok) {
        const data = await res.json();
        const arr = Array.isArray(data) ? data : [];
        setQuizzes(arr);
        cache[classSlug] = arr;
      }
    } catch {
      setQuizzes([]);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    async function init() {
      try {
        const classRes = await fetch("/api/classes");
        const classes = await classRes.json();
        const cls = classes.find((c: { slug: string }) => c.slug === classSlug);
        if (!cls) {
          setLoading(false);
          return;
        }
        setClassId(cls.id);
        fetchQuizzes(cls.id);
      } catch {
        setLoading(false);
      }
    }
    init();
  }, [classSlug, fetchQuizzes]);

  async function handleDelete(id: string, name: string) {
    if (!confirm(`Delete "${name}" and all its questions and attempts?`)) return;
    await fetch(`/api/quizzes/${id}`, { method: "DELETE" });
    setQuizzes((prev) => prev.filter((q) => q.id !== id));
  }

  return (
    <div className="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8">
      {/* Header */}
      <div className="flex items-center justify-between mb-6">
        <h2 className="text-xl font-semibold text-text-heading">Quizzes</h2>
        <button
          onClick={() => setShowImport(true)}
          className="inline-flex items-center gap-2 px-4 py-2.5 rounded-lg bg-primary text-white font-medium hover:bg-primary-hover transition-all duration-200 shadow-sm cursor-pointer"
        >
          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
          </svg>
          Import Quiz
        </button>
      </div>



      {/* Empty state */}
      {!loading && quizzes.length === 0 && (
        <div className={`text-center py-16 ${animate ? "animate-slide-up" : ""}`}>
          <div className="inline-flex items-center justify-center w-16 h-16 rounded-2xl bg-bg-callout mb-4">
            <svg className="w-8 h-8 text-primary" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
            </svg>
          </div>
          <h3 className="text-lg font-semibold text-text-heading mb-1">No quizzes yet</h3>
          <p className="text-text-secondary mb-4">Import your first quiz to start practicing</p>
          <button
            onClick={() => setShowImport(true)}
            className="inline-flex items-center gap-2 px-4 py-2.5 rounded-lg bg-primary text-white font-medium hover:bg-primary-hover transition-all duration-200 cursor-pointer"
          >
            Import Quiz
          </button>
        </div>
      )}

      {/* Quiz grid */}
      {!loading && quizzes.length > 0 && (
        <div className={`grid grid-cols-1 md:grid-cols-2 gap-4 ${animate ? "animate-slide-up" : ""}`}>
          {quizzes.map((quiz) => (
            <div
              key={quiz.id}
              className="group bg-bg-surface rounded-xl border border-border-light shadow-[var(--shadow-card)] hover:shadow-[var(--shadow-card-hover)] hover:border-primary/20 transition-all duration-300"
            >
              <div className="p-6">
                <h3 className="text-lg font-semibold text-text-heading mb-1">
                  {quiz.name}
                </h3>
                {quiz.description && (
                  <p className="text-sm text-text-secondary mb-3 line-clamp-2">
                    {quiz.description}
                  </p>
                )}
                <div className="flex items-center gap-3">
                  <span className="inline-flex items-center gap-1 px-2.5 py-1 rounded-full bg-badge-bg text-badge-text text-xs font-medium">
                    {quiz._count.questions} {quiz._count.questions === 1 ? "question" : "questions"}
                  </span>
                  {quiz._count.attempts > 0 && (
                    <span className="text-xs text-text-muted">
                      {quiz._count.attempts} {quiz._count.attempts === 1 ? "attempt" : "attempts"}
                    </span>
                  )}
                </div>

                <div className="flex items-center gap-2 mt-4 pt-4 border-t border-border-light">
                  <Link
                    href={`/${classSlug}/quizzes/${quiz.id}`}
                    className="flex-1 text-center py-2 px-4 rounded-lg bg-primary text-white text-sm font-medium hover:bg-primary-hover transition-all duration-200"
                  >
                    Start Quiz
                  </Link>
                  <button
                    onClick={() => handleDelete(quiz.id, quiz.name)}
                    className="p-2 rounded-lg text-text-muted hover:text-error hover:bg-error-bg transition-all duration-200 cursor-pointer"
                    title="Delete"
                  >
                    <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                    </svg>
                  </button>
                </div>
              </div>
            </div>
          ))}
        </div>
      )}

      {/* Import Modal */}
      {showImport && (
        <ImportModal
          classId={classId}
          importType="quizzes"
          onClose={() => setShowImport(false)}
          onImported={() => {
            setShowImport(false);
            window.location.reload();
          }}
        />
      )}
    </div>
  );
}
