"use client";

import * as React from "react";
import {
  Plus,
  Trash2,
  CheckCircle2,
  Layers,
  HelpCircle,
  FileCheck,
  Check,
} 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";

interface QuizBuilderClientProps {
  quiz: any;
}

export default function QuizBuilderClient({ quiz }: QuizBuilderClientProps) {
  const [questions, setQuestions] = React.useState(quiz.questions);
  const [addModalOpen, setAddModalOpen] = React.useState(false);

  // Form State
  const [type, setType] = React.useState<"MULTIPLE_CHOICE" | "TRUE_FALSE" | "SHORT_ANSWER" | "ESSAY">("MULTIPLE_CHOICE");
  const [questionText, setQuestionText] = React.useState("");
  const [scoreWeight, setScoreWeight] = React.useState("20");
  const [explanation, setExplanation] = React.useState("");

  // Multiple Choice Options
  const [mcOptions, setMcOptions] = React.useState([
    { label: "A", content: "", isCorrect: true },
    { label: "B", content: "", isCorrect: false },
    { label: "C", content: "", isCorrect: false },
    { label: "D", content: "", isCorrect: false },
    { label: "E", content: "", isCorrect: false },
  ]);

  // True False Option (true or false correct)
  const [tfCorrect, setTfCorrect] = React.useState<"Benar" | "Salah">("Benar");

  // Short Answer Keyword
  const [shortAnswerKey, setShortAnswerKey] = React.useState("");

  const [isLoading, setIsLoading] = React.useState(false);
  const [errorMsg, setErrorMsg] = React.useState("");

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

    let optionsPayload: any[] = [];
    if (type === "MULTIPLE_CHOICE") {
      optionsPayload = mcOptions.filter((o) => o.content.trim() !== "");
      if (optionsPayload.length < 2) {
        setErrorMsg("Pilihan ganda minimal memiliki 2 opsi jawaban.");
        setIsLoading(false);
        return;
      }
      if (!optionsPayload.some((o) => o.isCorrect)) {
        setErrorMsg("Pilih salah satu opsi sebagai kunci jawaban benar.");
        setIsLoading(false);
        return;
      }
    } else if (type === "TRUE_FALSE") {
      optionsPayload = [
        { label: "A", content: "Benar", isCorrect: tfCorrect === "Benar" },
        { label: "B", content: "Salah", isCorrect: tfCorrect === "Salah" },
      ];
    } else if (type === "SHORT_ANSWER") {
      if (!shortAnswerKey.trim()) {
        setErrorMsg("Kunci jawaban isian singkat wajib diisi.");
        setIsLoading(false);
        return;
      }
      optionsPayload = [{ label: "A", content: shortAnswerKey.trim(), isCorrect: true }];
    }

    try {
      const res = await fetch(`/api/quizzes/${quiz.id}/questions`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          orderNumber: questions.length + 1,
          type,
          question: questionText,
          scoreWeight: parseFloat(scoreWeight) || 10,
          explanation,
          options: optionsPayload,
        }),
      });

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

      setAddModalOpen(false);
      window.location.reload();
    } catch (err) {
      setErrorMsg("Terjadi gangguan server.");
      setIsLoading(false);
    }
  };

  return (
    <div className="space-y-6">
      {/* Top action bar */}
      <div className="flex items-center justify-between">
        <div>
          <span className="text-xs font-bold text-slate-700">
            Daftar Butir Soal ({questions.length} Soal)
          </span>
          <p className="text-[11px] text-slate-500">
            Total Bobot Skor: {questions.reduce((acc: number, q: any) => acc + q.scoreWeight, 0)} Poin
          </p>
        </div>

        <Button
          size="sm"
          onClick={() => setAddModalOpen(true)}
          className="font-bold text-xs"
        >
          <Plus className="mr-1.5 h-4 w-4" />
          Tambah Butir Soal
        </Button>
      </div>

      {/* Questions list */}
      <div className="space-y-4">
        {questions.length === 0 ? (
          <div className="p-12 text-center text-xs text-slate-400 border-2 border-dashed border-slate-200 rounded-2xl bg-white">
            <HelpCircle className="h-8 w-8 text-slate-300 mx-auto mb-2" />
            Belum ada soal pada ujian ini. Klik "Tambah Butir Soal" untuk mulai menyusun pertanyaan.
          </div>
        ) : (
          questions.map((q: any, idx: number) => {
            let typeBadge = "Pilihan Ganda";
            if (q.type === "TRUE_FALSE") typeBadge = "Benar / Salah";
            else if (q.type === "SHORT_ANSWER") typeBadge = "Isian Singkat";
            else if (q.type === "ESSAY") typeBadge = "Esai (Uraian)";

            return (
              <Card key={q.id} className="p-5 space-y-3">
                <div className="flex items-center justify-between border-b border-slate-100 pb-2">
                  <div className="flex items-center gap-2">
                    <span className="h-6 w-6 rounded-full bg-blue-600 text-white text-xs font-bold flex items-center justify-center">
                      {idx + 1}
                    </span>
                    <Badge variant="secondary">{typeBadge}</Badge>
                  </div>
                  <span className="text-xs font-bold text-blue-600 font-mono">
                    Bobot: {q.scoreWeight} Poin
                  </span>
                </div>

                <div className="text-sm font-semibold text-slate-800 leading-relaxed whitespace-pre-wrap">
                  {q.question}
                </div>

                {/* Options preview */}
                {q.options?.length > 0 && (
                  <div className="space-y-1.5 pt-1">
                    {q.options.map((opt: any) => (
                      <div
                        key={opt.id}
                        className={`flex items-center gap-2.5 p-2 rounded-lg text-xs border ${
                          opt.isCorrect
                            ? "bg-emerald-50/80 border-emerald-300 text-emerald-900 font-semibold"
                            : "bg-slate-50 border-slate-200 text-slate-700"
                        }`}
                      >
                        <span
                          className={`h-5 w-5 rounded-full flex items-center justify-center text-[10px] font-bold shrink-0 ${
                            opt.isCorrect
                              ? "bg-emerald-600 text-white"
                              : "bg-slate-200 text-slate-600"
                          }`}
                        >
                          {opt.label}
                        </span>
                        <span className="flex-1">{opt.content}</span>
                        {opt.isCorrect && (
                          <span className="text-[10px] font-bold text-emerald-700 flex items-center gap-0.5 shrink-0">
                            <Check className="h-3 w-3" /> Kunci Jawaban
                          </span>
                        )}
                      </div>
                    ))}
                  </div>
                )}

                {q.explanation && (
                  <p className="text-[11px] text-slate-500 italic pt-1">
                    Pembahasan: {q.explanation}
                  </p>
                )}
              </Card>
            );
          })
        )}
      </div>

      {/* Modal Tambah Butir Soal */}
      <Modal
        isOpen={addModalOpen}
        onClose={() => setAddModalOpen(false)}
        title="Tambah Butir Soal Baru"
        description="Pilih tipe soal dan tentukan kunci jawaban yang benar."
        maxWidth="xl"
      >
        <form onSubmit={handleCreateQuestion} 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>
          )}

          <div className="grid grid-cols-2 gap-3">
            <Select
              label="Tipe Soal"
              value={type}
              onChange={(e) => setType(e.target.value as any)}
            >
              <option value="MULTIPLE_CHOICE">Pilihan Ganda (PG)</option>
              <option value="TRUE_FALSE">Benar / Salah</option>
              <option value="SHORT_ANSWER">Isian Singkat</option>
              <option value="ESSAY">Esai / Uraian</option>
            </Select>

            <Input
              label="Bobot Skor Soal"
              type="number"
              value={scoreWeight}
              onChange={(e) => setScoreWeight(e.target.value)}
              required
            />
          </div>

          <Textarea
            label="Teks Pertanyaan"
            placeholder="Tuliskan teks pertanyaan soal secara lengkap..."
            rows={3}
            value={questionText}
            onChange={(e) => setQuestionText(e.target.value)}
            required
          />

          {/* Opsi Pilihan Ganda */}
          {type === "MULTIPLE_CHOICE" && (
            <div className="space-y-2 pt-2 border-t border-slate-100">
              <label className="block text-xs font-bold text-slate-700">
                Opsi Pilihan Ganda & Kunci Jawaban:
              </label>
              {mcOptions.map((opt, i) => (
                <div key={opt.label} className="flex items-center gap-2">
                  <button
                    type="button"
                    onClick={() => {
                      setMcOptions((prev) =>
                        prev.map((o, idx) => ({ ...o, isCorrect: idx === i }))
                      );
                    }}
                    className={`h-7 w-7 rounded-lg font-bold text-xs shrink-0 transition-colors ${
                      opt.isCorrect
                        ? "bg-emerald-600 text-white shadow-sm"
                        : "bg-slate-100 text-slate-600 hover:bg-slate-200"
                    }`}
                    title="Jadikan Kunci Jawaban"
                  >
                    {opt.label}
                  </button>
                  <input
                    type="text"
                    placeholder={`Teks jawaban pilihan ${opt.label}...`}
                    value={opt.content}
                    onChange={(e) => {
                      const val = e.target.value;
                      setMcOptions((prev) =>
                        prev.map((o, idx) => (idx === i ? { ...o, content: val } : o))
                      );
                    }}
                    className="w-full text-xs px-3 py-1.5 rounded-lg border border-slate-300 focus:outline-none focus:ring-2 focus:ring-blue-500"
                  />
                </div>
              ))}
              <p className="text-[10px] text-slate-400">
                * Klik tombol huruf (A/B/C/D/E) yang berwarna hijau untuk memilih kunci jawaban benar.
              </p>
            </div>
          )}

          {/* Opsi Benar / Salah */}
          {type === "TRUE_FALSE" && (
            <div className="space-y-2 pt-2 border-t border-slate-100">
              <label className="block text-xs font-bold text-slate-700">
                Kunci Jawaban Pernyataan:
              </label>
              <div className="flex gap-4 text-xs font-semibold">
                <label className="flex items-center gap-2 cursor-pointer">
                  <input
                    type="radio"
                    name="tfCorrect"
                    checked={tfCorrect === "Benar"}
                    onChange={() => setTfCorrect("Benar")}
                    className="text-emerald-600"
                  />
                  <span>Pernyataan Benar</span>
                </label>
                <label className="flex items-center gap-2 cursor-pointer">
                  <input
                    type="radio"
                    name="tfCorrect"
                    checked={tfCorrect === "Salah"}
                    onChange={() => setTfCorrect("Salah")}
                    className="text-rose-600"
                  />
                  <span>Pernyataan Salah</span>
                </label>
              </div>
            </div>
          )}

          {/* Opsi Isian Singkat */}
          {type === "SHORT_ANSWER" && (
            <div className="pt-2 border-t border-slate-100">
              <Input
                label="Kunci Jawaban Isian Singkat (Kata Kunci Pasti)"
                placeholder="Contoh: 12 atau Fotosintesis"
                value={shortAnswerKey}
                onChange={(e) => setShortAnswerKey(e.target.value)}
                required
              />
            </div>
          )}

          {/* Opsi Esai */}
          {type === "ESSAY" && (
            <div className="p-3 rounded-lg bg-blue-50 border border-blue-100 text-xs text-blue-800">
              Soal tipe Esai akan dijawab siswa dalam bentuk teks uraian bebas dan diperiksa secara manual oleh guru pada menu Hasil Ujian.
            </div>
          )}

          <Textarea
            label="Pembahasan Soal (Opsional)"
            placeholder="Penjelasan langkah penyelesaian untuk siswa..."
            rows={2}
            value={explanation}
            onChange={(e) => setExplanation(e.target.value)}
          />

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