"use client";

import * as React from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import {
  Plus,
  Search,
  FileCheck,
  Clock,
  Shuffle,
  Award,
  Users,
  Layers,
  ArrowRight,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Modal } from "@/components/ui/modal";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Select } from "@/components/ui/select";
import { formatDateID } from "@/lib/utils";

interface TeacherQuizzesClientProps {
  initialQuizzes: any[];
  teacherSubjects: any[];
}

export default function TeacherQuizzesClient({
  initialQuizzes,
  teacherSubjects,
}: TeacherQuizzesClientProps) {
  const router = useRouter();
  const [quizzes, setQuizzes] = React.useState(initialQuizzes);
  const [selectedTS, setSelectedTS] = React.useState("ALL");
  const [search, setSearch] = React.useState("");

  // Create Modal
  const [createModalOpen, setCreateModalOpen] = React.useState(false);
  const [tsId, setTsId] = React.useState(teacherSubjects[0]?.id || "");
  const [title, setTitle] = React.useState("");
  const [description, setDescription] = React.useState("");
  const [durationMinutes, setDurationMinutes] = React.useState("60");
  const [passingScore, setPassingScore] = React.useState("75");
  const [startTime, setStartTime] = React.useState("");
  const [endTime, setEndTime] = React.useState("");
  const [randomizeQuestions, setRandomizeQuestions] = React.useState(true);
  const [randomizeOptions, setRandomizeOptions] = React.useState(true);
  const [maxAttempts, setMaxAttempts] = React.useState("1");
  const [isLoading, setIsLoading] = React.useState(false);
  const [errorMsg, setErrorMsg] = React.useState("");

  const filteredQuizzes = quizzes.filter((q) => {
    const matchTS = selectedTS === "ALL" || q.teacherSubjectId === selectedTS;
    const matchSearch =
      q.title.toLowerCase().includes(search.toLowerCase()) ||
      q.teacherSubject.subject.name.toLowerCase().includes(search.toLowerCase());
    return matchTS && matchSearch;
  });

  const handleCreateQuiz = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsLoading(true);
    setErrorMsg("");

    try {
      const res = await fetch("/api/quizzes", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          teacherSubjectId: tsId,
          title,
          description,
          durationMinutes: parseInt(durationMinutes) || 60,
          passingScore: parseFloat(passingScore) || 75,
          startTime: new Date(startTime).toISOString(),
          endTime: new Date(endTime).toISOString(),
          randomizeQuestions,
          randomizeOptions,
          maxAttempts: parseInt(maxAttempts) || 1,
        }),
      });

      const data = await res.json();
      if (!res.ok || !data.success) {
        setErrorMsg(data.error || "Gagal membuat kuis.");
        setIsLoading(false);
        return;
      }

      setCreateModalOpen(false);
      router.push(`/teacher/quizzes/${data.data.id}/builder`);
    } catch (err) {
      setErrorMsg("Terjadi gangguan jaringan.");
      setIsLoading(false);
    }
  };

  return (
    <div className="space-y-6">
      {/* Filters and Action */}
      <div className="flex flex-col sm:flex-row items-center justify-between gap-4">
        <div className="flex flex-wrap items-center gap-2 w-full sm:w-auto">
          <Select
            value={selectedTS}
            onChange={(e) => setSelectedTS(e.target.value)}
            className="w-full sm:w-64"
          >
            <option value="ALL">Semua Kelas & Mapel</option>
            {teacherSubjects.map((ts) => (
              <option key={ts.id} value={ts.id}>
                {ts.subject.name} - Kelas {ts.class.name}
              </option>
            ))}
          </Select>

          <div className="relative flex-1 sm:w-64">
            <Search className="absolute left-3 top-2.5 h-4 w-4 text-slate-400" />
            <input
              type="text"
              placeholder="Cari judul kuis/ujian..."
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              className="w-full pl-9 pr-3 py-2 rounded-xl border border-slate-200 text-xs bg-white text-slate-800 placeholder:text-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-500"
            />
          </div>
        </div>

        <Button
          size="sm"
          onClick={() => setCreateModalOpen(true)}
          className="w-full sm:w-auto font-bold text-xs"
        >
          <Plus className="mr-1.5 h-4 w-4" />
          Buat Ujian CBT Baru
        </Button>
      </div>

      {/* Grid of Quizzes */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-5">
        {filteredQuizzes.map((q) => (
          <Card
            key={q.id}
            className="hover:border-blue-400 hover:shadow-md transition-all flex flex-col justify-between group"
          >
            <CardHeader className="pb-2">
              <div className="flex items-center justify-between">
                <Badge variant="primary">{q.teacherSubject.class.name}</Badge>
                <span className="text-xs font-mono font-bold text-slate-700 bg-slate-100 px-2 py-0.5 rounded-full">
                  {q.durationMinutes} Menit
                </span>
              </div>
              <p className="text-[11px] font-bold text-blue-600 mt-1">
                {q.teacherSubject.subject.name}
              </p>
              <CardTitle className="text-base text-slate-900 line-clamp-2">
                {q.title}
              </CardTitle>
            </CardHeader>

            <CardContent className="space-y-3 pt-2">
              {q.description && (
                <p className="text-xs text-slate-500 line-clamp-2 leading-relaxed">
                  {q.description}
                </p>
              )}

              {/* Stats & Features */}
              <div className="grid grid-cols-2 gap-2 text-xs">
                <div className="p-2.5 rounded-xl bg-slate-50 border border-slate-100 text-center">
                  <span className="text-[10px] text-slate-400 block">Butir Soal</span>
                  <span className="font-bold text-slate-800 text-sm">
                    {q.questions?.length || 0} Soal
                  </span>
                </div>
                <div className="p-2.5 rounded-xl bg-slate-50 border border-slate-100 text-center">
                  <span className="text-[10px] text-slate-400 block">Siswa Mengikuti</span>
                  <span className="font-bold text-slate-800 text-sm">
                    {q.attempts?.length || 0} Siswa
                  </span>
                </div>
              </div>

              <div className="space-y-1 text-[11px] text-slate-500 pt-1">
                <p>KKM / Passing: <strong>{q.passingScore}</strong></p>
                <p>Batas Percobaan: <strong>{q.maxAttempts}x Ujian</strong></p>
              </div>

              {/* Actions */}
              <div className="pt-2 border-t border-slate-100 grid grid-cols-2 gap-2">
                <Link href={`/teacher/quizzes/${q.id}/builder`}>
                  <Button size="sm" variant="outline" className="w-full text-xs font-bold">
                    <Layers className="mr-1 h-3.5 w-3.5 text-blue-600" />
                    Bank Soal
                  </Button>
                </Link>

                <Link href={`/teacher/quizzes/${q.id}/results`}>
                  <Button size="sm" className="w-full text-xs font-bold">
                    <Award className="mr-1 h-3.5 w-3.5" />
                    Hasil Ujian
                  </Button>
                </Link>
              </div>
            </CardContent>
          </Card>
        ))}
      </div>

      {/* Modal Buat Ujian CBT */}
      <Modal
        isOpen={createModalOpen}
        onClose={() => setCreateModalOpen(false)}
        title="Buat Ujian CBT Baru"
        description="Atur durasi timer, waktu aktifasi, dan konfigurasi acak soal."
        maxWidth="xl"
      >
        <form onSubmit={handleCreateQuiz} className="space-y-4">
          {errorMsg && (
            <div className="p-3 rounded-lg bg-rose-50 border border-rose-200 text-rose-700 text-xs">
              {errorMsg}
            </div>
          )}

          <Select
            label="Mata Pelajaran & Kelas"
            value={tsId}
            onChange={(e) => setTsId(e.target.value)}
          >
            {teacherSubjects.map((ts) => (
              <option key={ts.id} value={ts.id}>
                {ts.subject.name} - Kelas {ts.class.name}
              </option>
            ))}
          </Select>

          <Input
            label="Judul Ujian / Kuis"
            placeholder="Contoh: Asesmen Sumatif Tengah Semester (ASTS) Matematika"
            value={title}
            onChange={(e) => setTitle(e.target.value)}
            required
          />

          <Input
            label="Deskripsi Singkat"
            placeholder="Keterangan cakupan bab materi..."
            value={description}
            onChange={(e) => setDescription(e.target.value)}
          />

          <div className="grid grid-cols-2 gap-3">
            <Input
              label="Durasi Pengerjaan (Menit)"
              type="number"
              min="5"
              max="240"
              value={durationMinutes}
              onChange={(e) => setDurationMinutes(e.target.value)}
              required
            />
            <Input
              label="Nilai KKM (Passing Score)"
              type="number"
              min="0"
              max="100"
              value={passingScore}
              onChange={(e) => setPassingScore(e.target.value)}
              required
            />
          </div>

          <div className="grid grid-cols-2 gap-3">
            <Input
              label="Jadwal Waktu Mulai"
              type="datetime-local"
              value={startTime}
              onChange={(e) => setStartTime(e.target.value)}
              required
            />
            <Input
              label="Jadwal Waktu Selesai"
              type="datetime-local"
              value={endTime}
              onChange={(e) => setEndTime(e.target.value)}
              required
            />
          </div>

          <div className="grid grid-cols-2 gap-3 pt-2 border-t border-slate-100">
            <label className="flex items-center gap-2 text-xs text-slate-700 cursor-pointer">
              <input
                type="checkbox"
                checked={randomizeQuestions}
                onChange={(e) => setRandomizeQuestions(e.target.checked)}
                className="h-4 w-4 rounded border-slate-300 text-blue-600"
              />
              <span>Acak Urutan Soal Siswa</span>
            </label>

            <label className="flex items-center gap-2 text-xs text-slate-700 cursor-pointer">
              <input
                type="checkbox"
                checked={randomizeOptions}
                onChange={(e) => setRandomizeOptions(e.target.checked)}
                className="h-4 w-4 rounded border-slate-300 text-blue-600"
              />
              <span>Acak Opsi Pilihan Ganda</span>
            </label>
          </div>

          <div className="flex justify-end gap-2.5 pt-4 border-t border-slate-100">
            <Button
              type="button"
              variant="outline"
              size="sm"
              onClick={() => setCreateModalOpen(false)}
            >
              Batal
            </Button>
            <Button type="submit" size="sm" isLoading={isLoading}>
              Simpan & Lanjut Buat Soal
            </Button>
          </div>
        </form>
      </Modal>
    </div>
  );
}
