"use client";

import * as React from "react";
import { useActionState } from "react";
import {
  CheckCircle2,
  GripVertical,
  Plus,
  Trash2,
  TriangleAlert,
} from "lucide-react";
import { Alert } from "@/components/ui/alert";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Field, Input, Select, Textarea } from "@/components/ui/input";
import { Checkbox } from "@/components/ui/checkbox";
import { saveQuizAction } from "@/actions/quizzes";
import { IDLE_ACTION } from "@/lib/action-state";
import type { StaffQuiz } from "@/lib/queries/quizzes";
import type { QuestionType } from "@prisma/client";

/**
 * Quiz authoring.
 *
 * The question set is edited as local state and posted as one JSON field. It
 * could have been a plain nested form, but every question has a different shape
 * depending on its type, and a single payload keeps the server's validation in
 * one schema rather than spread across a dozen indexed field names.
 *
 * Questions that students have already answered are locked: the server keeps
 * them regardless, so letting the author delete one here would produce a silent
 * disagreement between the form and the saved quiz.
 */

const TYPE_OPTIONS: Array<{ value: QuestionType; label: string; hint: string }> = [
  { value: "MULTIPLE_CHOICE", label: "Pilihan ganda", hint: "Satu jawaban benar." },
  { value: "MULTI_SELECT", label: "Pilihan ganda (banyak jawaban)", hint: "Beberapa jawaban benar." },
  { value: "TRUE_FALSE", label: "Benar / Salah", hint: "Dua pilihan saja." },
  { value: "SHORT_ANSWER", label: "Jawaban singkat", hint: "Dinilai otomatis dari teks." },
  { value: "CODE", label: "Kode", hint: "Dinilai manual oleh pengajar." },
];

interface DraftQuestion {
  /** Set for a question that already exists in the database. */
  id?: string;
  prompt: string;
  type: QuestionType;
  options: string[];
  /** Index, indices, or text — matching the type. */
  correctAnswer: number | number[] | string;
  explanation: string;
  points: number;
  /** True when students have answered it, so it cannot be removed. */
  locked?: boolean;
}

function emptyQuestion(): DraftQuestion {
  return {
    prompt: "",
    type: "MULTIPLE_CHOICE",
    options: ["", ""],
    correctAnswer: 0,
    explanation: "",
    points: 1,
  };
}

/** Coerce a stored answer key into the shape the editor's controls expect. */
function toDraftAnswer(type: QuestionType, value: unknown): number | number[] | string {
  if (type === "MULTI_SELECT") {
    return Array.isArray(value)
      ? value.filter((entry): entry is number => typeof entry === "number")
      : [];
  }
  if (type === "SHORT_ANSWER" || type === "CODE") {
    return typeof value === "string" ? value : "";
  }
  return typeof value === "number" ? value : 0;
}

export function QuizEditor({ quiz }: { quiz: StaffQuiz }) {
  const [state, formAction, pending] = useActionState(saveQuizAction, IDLE_ACTION);

  const [questions, setQuestions] = React.useState<DraftQuestion[]>(() =>
    quiz.questions.map((question) => ({
      id: question.id,
      prompt: question.prompt,
      type: question.type,
      options: question.options.length > 0 ? question.options : ["", ""],
      correctAnswer: toDraftAnswer(question.type, question.correctAnswer),
      explanation: question.explanation ?? "",
      points: question.points,
      locked: question.answeredCount > 0,
    }))
  );

  const [passingScore, setPassingScore] = React.useState(String(quiz.passingScore));
  const [timeLimit, setTimeLimit] = React.useState(
    quiz.timeLimitMinutes === null ? "" : String(quiz.timeLimitMinutes)
  );
  const [shuffle, setShuffle] = React.useState(quiz.shuffleQuestions);
  const [allowRetakes, setAllowRetakes] = React.useState(quiz.allowRetakes);
  const [maxAttempts, setMaxAttempts] = React.useState(String(quiz.maxAttempts));

  const totalPoints = questions.reduce((sum, question) => sum + question.points, 0);
  const errors = state.status === "error" ? state.errors : undefined;

  function updateQuestion(index: number, patch: Partial<DraftQuestion>) {
    setQuestions((current) =>
      current.map((question, position) =>
        position === index ? { ...question, ...patch } : question
      )
    );
  }

  /**
   * Switching type rebuilds the answer key.
   *
   * A stale key is worse than a blank one: a MULTI_SELECT key is an array of
   * indices, and reusing it as a single-choice index would silently mark the
   * wrong option correct.
   */
  function changeType(index: number, type: QuestionType) {
    const defaults: Partial<DraftQuestion> = { type };

    if (type === "TRUE_FALSE") {
      defaults.options = ["Benar", "Salah"];
      defaults.correctAnswer = 0;
    } else if (type === "MULTI_SELECT") {
      const existing = questions[index]?.options ?? [];
      defaults.options = existing.length >= 2 ? existing : ["", ""];
      defaults.correctAnswer = [];
    } else if (type === "SHORT_ANSWER" || type === "CODE") {
      defaults.options = [];
      defaults.correctAnswer = "";
    } else {
      const existing = questions[index]?.options ?? [];
      defaults.options = existing.length >= 2 ? existing : ["", ""];
      defaults.correctAnswer = 0;
    }

    updateQuestion(index, defaults);
  }

  function addQuestion() {
    setQuestions((current) => [...current, emptyQuestion()]);
  }

  function removeQuestion(index: number) {
    setQuestions((current) => current.filter((_, position) => position !== index));
  }

  function setOption(questionIndex: number, optionIndex: number, value: string) {
    setQuestions((current) =>
      current.map((question, position) =>
        position === questionIndex
          ? {
              ...question,
              options: question.options.map((option, index) =>
                index === optionIndex ? value : option
              ),
            }
          : question
      )
    );
  }

  function addOption(questionIndex: number) {
    setQuestions((current) =>
      current.map((question, position) =>
        position === questionIndex && question.options.length < 10
          ? { ...question, options: [...question.options, ""] }
          : question
      )
    );
  }

  function removeOption(questionIndex: number, optionIndex: number) {
    setQuestions((current) =>
      current.map((question, position) => {
        if (position !== questionIndex) return question;

        const options = question.options.filter((_, index) => index !== optionIndex);
        // Every key that referred to a later option shifts down by one.
        const shift = (value: number) => (value > optionIndex ? value - 1 : value);

        let correctAnswer = question.correctAnswer;
        if (Array.isArray(correctAnswer)) {
          correctAnswer = correctAnswer
            .filter((value) => value !== optionIndex)
            .map(shift);
        } else if (typeof correctAnswer === "number") {
          correctAnswer = correctAnswer === optionIndex ? 0 : shift(correctAnswer);
        }

        return { ...question, options, correctAnswer };
      })
    );
  }

  return (
    <form action={formAction} className="space-y-6">
      <input type="hidden" name="assignmentId" value={quiz.assignmentId} />
      <input type="hidden" name="questions" value={JSON.stringify(questions)} />
      {/* Checkboxes only submit when ticked, so an explicit value is posted. */}
      <input type="hidden" name="shuffleQuestions" value={shuffle ? "on" : "off"} />
      <input type="hidden" name="allowRetakes" value={allowRetakes ? "on" : "off"} />

      {state.status === "error" ? (
        <Alert tone="danger" title="Kuis belum dapat disimpan">
          {state.message}
        </Alert>
      ) : null}

      {state.status === "success" ? <Alert tone="success">{state.message}</Alert> : null}

      <Card>
        <CardHeader>
          <CardTitle>Pengaturan kuis</CardTitle>
        </CardHeader>
        <CardContent className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
          <Field
            label="Ambang kelulusan (%)"
            htmlFor="passingScore"
            error={errors?.passingScore}
            required
          >
            <Input
              id="passingScore"
              name="passingScore"
              type="number"
              min={0}
              max={100}
              value={passingScore}
              onChange={(event) => setPassingScore(event.target.value)}
            />
          </Field>

          <Field
            label="Batas waktu (menit)"
            htmlFor="timeLimitMinutes"
            hint="Kosongkan bila tanpa batas waktu."
            error={errors?.timeLimitMinutes}
          >
            <Input
              id="timeLimitMinutes"
              name="timeLimitMinutes"
              type="number"
              min={0}
              max={600}
              placeholder="Tanpa batas"
              value={timeLimit}
              onChange={(event) => setTimeLimit(event.target.value)}
            />
          </Field>

          <Field
            label="Maksimal percobaan"
            htmlFor="maxAttempts"
            error={errors?.maxAttempts}
            required
          >
            <Input
              id="maxAttempts"
              name="maxAttempts"
              type="number"
              min={1}
              max={20}
              value={maxAttempts}
              onChange={(event) => setMaxAttempts(event.target.value)}
              disabled={!allowRetakes}
            />
          </Field>

          <div className="space-y-3 pt-6">
            <label className="flex items-center gap-2 text-sm text-primary">
              <Checkbox
                checked={shuffle}
                onCheckedChange={(checked) => setShuffle(checked === true)}
              />
              Acak urutan soal
            </label>
            <label className="flex items-center gap-2 text-sm text-primary">
              <Checkbox
                checked={allowRetakes}
                onCheckedChange={(checked) => {
                  const next = checked === true;
                  setAllowRetakes(next);
                  if (!next) setMaxAttempts("1");
                }}
              />
              Izinkan percobaan ulang
            </label>
          </div>
        </CardContent>
      </Card>

      <div className="flex flex-wrap items-center justify-between gap-3">
        <div className="flex items-center gap-2">
          <Badge variant="brand">{questions.length} soal</Badge>
          <Badge variant="neutral">Total {totalPoints} poin</Badge>
        </div>
        <Button type="button" variant="secondary" onClick={addQuestion}>
          <Plus className="size-4" />
          Tambah soal
        </Button>
      </div>

      {errors?.questions ? (
        <Alert tone="danger" title="Periksa kembali soal">
          {errors.questions}
        </Alert>
      ) : null}

      {questions.length === 0 ? (
        <Card>
          <CardContent className="py-10 text-center text-sm text-tertiary">
            Belum ada soal. Tambahkan minimal satu soal agar kuis dapat dikerjakan.
          </CardContent>
        </Card>
      ) : null}

      {questions.map((question, index) => (
        <QuestionEditor
          key={question.id ?? `new-${index}`}
          question={question}
          number={index + 1}
          error={errors?.[`questions.${index}.prompt`]}
          onChange={(patch) => updateQuestion(index, patch)}
          onTypeChange={(type) => changeType(index, type)}
          onOptionChange={(optionIndex, value) => setOption(index, optionIndex, value)}
          onAddOption={() => addOption(index)}
          onRemoveOption={(optionIndex) => removeOption(index, optionIndex)}
          onRemove={() => removeQuestion(index)}
        />
      ))}

      <div className="flex justify-end gap-2">
        <Button type="submit" disabled={pending || questions.length === 0}>
          {pending ? "Menyimpan…" : "Simpan kuis"}
        </Button>
      </div>
    </form>
  );
}

function QuestionEditor({
  question,
  number,
  error,
  onChange,
  onTypeChange,
  onOptionChange,
  onAddOption,
  onRemoveOption,
  onRemove,
}: {
  question: DraftQuestion;
  number: number;
  error?: string;
  onChange: (patch: Partial<DraftQuestion>) => void;
  onTypeChange: (type: QuestionType) => void;
  onOptionChange: (optionIndex: number, value: string) => void;
  onAddOption: () => void;
  onRemoveOption: (optionIndex: number) => void;
  onRemove: () => void;
}) {
  const hasOptions =
    question.type === "MULTIPLE_CHOICE" ||
    question.type === "MULTI_SELECT" ||
    question.type === "TRUE_FALSE";
  const isMulti = question.type === "MULTI_SELECT";
  const selected = Array.isArray(question.correctAnswer) ? question.correctAnswer : [];

  return (
    <Card>
      <CardHeader>
        <div className="flex flex-wrap items-center justify-between gap-3">
          <CardTitle className="flex items-center gap-2">
            <GripVertical className="size-4 text-tertiary" />
            Soal {number}
          </CardTitle>
          <div className="flex items-center gap-2">
            {question.locked ? <Badge variant="warning">Sudah dijawab siswa</Badge> : null}
            <Button
              type="button"
              variant="ghost"
              size="sm"
              onClick={onRemove}
              disabled={question.locked}
              title={
                question.locked
                  ? "Soal ini sudah dijawab siswa sehingga tidak dapat dihapus."
                  : "Hapus soal"
              }
            >
              <Trash2 className="size-4" />
            </Button>
          </div>
        </div>
      </CardHeader>

      <CardContent className="space-y-4">
        <div className="grid gap-4 sm:grid-cols-3">
          <Field label="Tipe soal" htmlFor={`type-${number}`} className="sm:col-span-2">
            <Select
              id={`type-${number}`}
              value={question.type}
              onChange={(event) => onTypeChange(event.target.value as QuestionType)}
            >
              {TYPE_OPTIONS.map((option) => (
                <option key={option.value} value={option.value}>
                  {option.label}
                </option>
              ))}
            </Select>
          </Field>

          <Field label="Poin" htmlFor={`points-${number}`} required>
            <Input
              id={`points-${number}`}
              type="number"
              min={1}
              max={100}
              value={question.points}
              onChange={(event) => onChange({ points: Number(event.target.value) || 1 })}
            />
          </Field>
        </div>

        <Field label="Pertanyaan" htmlFor={`prompt-${number}`} error={error} required>
          <Textarea
            id={`prompt-${number}`}
            rows={2}
            value={question.prompt}
            onChange={(event) => onChange({ prompt: event.target.value })}
            placeholder="Tulis pertanyaan di sini"
          />
        </Field>

        {hasOptions ? (
          <div className="space-y-2">
            <p className="ws-label text-secondary">
              Pilihan jawaban
              <span className="ml-2 font-normal normal-case text-tertiary">
                {isMulti ? "Centang semua jawaban benar." : "Pilih satu jawaban benar."}
              </span>
            </p>

            {question.options.map((option, index) => {
              const isCorrect = isMulti ? selected.includes(index) : question.correctAnswer === index;
              const lockedTrueFalse = question.type === "TRUE_FALSE";

              return (
                <div key={index} className="flex items-center gap-2">
                  {isMulti ? (
                    <Checkbox
                      checked={isCorrect}
                      disabled={lockedTrueFalse}
                      onCheckedChange={(checked) => {
                        const next =
                          checked === true
                            ? [...new Set([...selected, index])].sort((a, b) => a - b)
                            : selected.filter((value) => value !== index);
                        onChange({ correctAnswer: next });
                      }}
                    />
                  ) : (
                    <input
                      type="radio"
                      name={`correct-${number}`}
                      className="size-4"
                      checked={isCorrect}
                      disabled={lockedTrueFalse}
                      onChange={() => onChange({ correctAnswer: index })}
                    />
                  )}

                  <Input
                    value={option}
                    disabled={lockedTrueFalse}
                    onChange={(event) => onOptionChange(index, event.target.value)}
                    placeholder={`Pilihan ${String.fromCharCode(65 + index)}`}
                  />

                  <Button
                    type="button"
                    variant="ghost"
                    size="sm"
                    disabled={question.options.length <= 2 || lockedTrueFalse}
                    onClick={() => onRemoveOption(index)}
                    title="Hapus pilihan"
                  >
                    <Trash2 className="size-4" />
                  </Button>
                </div>
              );
            })}

            {question.type !== "TRUE_FALSE" && question.options.length < 10 ? (
              <Button type="button" variant="secondary" size="sm" onClick={onAddOption}>
                <Plus className="size-4" />
                Tambah pilihan
              </Button>
            ) : null}
          </div>
        ) : null}

        {question.type === "SHORT_ANSWER" ? (
          <Field
            label="Kunci jawaban"
            htmlFor={`key-${number}`}
            hint="Perbandingan mengabaikan huruf besar/kecil, spasi berlebih, dan tanda baca di akhir."
            required
          >
            <Input
              id={`key-${number}`}
              value={typeof question.correctAnswer === "string" ? question.correctAnswer : ""}
              onChange={(event) => onChange({ correctAnswer: event.target.value })}
              placeholder="mis. abstraksi"
            />
          </Field>
        ) : null}

        {question.type === "CODE" ? (
          <div className="flex items-start gap-3 rounded-md border border-info-100 bg-info-50 p-3 text-sm text-info-700 dark:border-info-700/40 dark:bg-info-700/10 dark:text-info-500">
            <TriangleAlert className="mt-0.5 size-4 shrink-0" />
            <span>
              Soal kode tidak dapat dinilai otomatis. Jawaban siswa dinilai langsung pada
              lembar jawabannya di halaman hasil kuis.
            </span>
          </div>
        ) : null}

        <Field
          label="Pembahasan"
          htmlFor={`explanation-${number}`}
          hint="Ditampilkan kepada siswa setelah kuis dikumpulkan."
        >
          <Textarea
            id={`explanation-${number}`}
            rows={2}
            value={question.explanation}
            onChange={(event) => onChange({ explanation: event.target.value })}
            placeholder="Jelaskan mengapa jawaban itu benar"
          />
        </Field>

        {question.type === "CODE" ? null : (
          <p className="inline-flex items-center gap-2 text-xs text-tertiary">
            <CheckCircle2 className="size-3" />
            Soal ini akan dinilai otomatis begitu siswa mengumpulkan jawaban.
          </p>
        )}
      </CardContent>
    </Card>
  );
}
