"use client";

import * as React from "react";
import { useActionState } from "react";
import { AlertTriangle, CheckCircle2, CircleHelp, Clock, Send } 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 { Progress } from "@/components/ui/progress";
import { Textarea } from "@/components/ui/input";
import { Checkbox } from "@/components/ui/checkbox";
import {
  Dialog,
  DialogClose,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { submitQuizAttemptAction, expireQuizAttemptAction } from "@/actions/quizzes";
import { IDLE_ACTION } from "@/lib/action-state";
import type { ActiveAttempt, StudentQuestion } from "@/lib/queries/quizzes";

/**
 * The quiz paper a student answers.
 *
 * Two things here are load-bearing:
 *
 *   • Answers are mirrored to `localStorage` as they are given. A quiz is the
 *     one place in the app where losing a page — a flat battery, a stray
 *     refresh, a phone call — destroys work that cannot be redone, because the
 *     attempt is already spent. The mirror is keyed by attempt id, so it cannot
 *     leak between attempts or students.
 *
 *   • The clock is authoritative on the server. This countdown is a courtesy;
 *     the deadline is recomputed from `startedAt` whenever the attempt is
 *     submitted, so a tampered clock in the browser cannot buy extra time.
 */

/** One answer as the form holds it: an index, indices, or free text. */
type AnswerValue = number | number[] | string | null;

const STORAGE_PREFIX = "robolearn:quiz:";

function storageKey(attemptId: string): string {
  return `${STORAGE_PREFIX}${attemptId}`;
}

function isAnswerValue(value: unknown): value is AnswerValue {
  if (value === null) return true;
  if (typeof value === "number") return Number.isInteger(value) && value >= 0;
  if (typeof value === "string") return true;
  if (Array.isArray(value)) {
    return value.every((entry) => typeof entry === "number" && Number.isInteger(entry) && entry >= 0);
  }
  return false;
}

/**
 * Recover mirrored answers, keeping only what still fits the paper.
 *
 * Answers are matched against the question currently on the page, so a draft
 * written before the author edited the quiz cannot restore a choice that no
 * longer exists — or, worse, restore an index that now points at a different
 * option.
 */
function restoreAnswers(
  questions: readonly StudentQuestion[],
  raw: string | null
): Record<string, AnswerValue> {
  if (!raw) return {};

  let parsed: unknown;
  try {
    parsed = JSON.parse(raw);
  } catch {
    return {};
  }

  if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) return {};

  const restored: Record<string, AnswerValue> = {};
  for (const question of questions) {
    const value = (parsed as Record<string, unknown>)[question.id];
    if (!isAnswerValue(value)) continue;

    // Drop an index that no longer addresses a real option.
    if (question.type === "MULTIPLE_CHOICE" || question.type === "TRUE_FALSE") {
      if (typeof value !== "number" || value >= question.options.length) continue;
    }
    if (question.type === "MULTI_SELECT") {
      if (!Array.isArray(value) || value.some((index) => index >= question.options.length)) continue;
    }
    if (question.type === "SHORT_ANSWER" || question.type === "CODE") {
      if (typeof value !== "string") continue;
    }

    restored[question.id] = value;
  }
  return restored;
}

/** mm:ss, or h:mm:ss once past an hour. */
function formatClock(totalSeconds: number): string {
  const hours = Math.floor(totalSeconds / 3600);
  const minutes = Math.floor((totalSeconds % 3600) / 60);
  const seconds = totalSeconds % 60;
  const pad = (value: number) => String(value).padStart(2, "0");
  return hours > 0 ? `${hours}:${pad(minutes)}:${pad(seconds)}` : `${minutes}:${pad(seconds)}`;
}

const TYPE_LABEL: Record<StudentQuestion["type"], string> = {
  MULTIPLE_CHOICE: "Pilih satu jawaban",
  MULTI_SELECT: "Pilih semua jawaban yang benar",
  TRUE_FALSE: "Benar atau salah",
  SHORT_ANSWER: "Jawaban singkat",
  CODE: "Jawaban kode",
};

export function QuizRunner({ attempt }: { attempt: ActiveAttempt }) {
  const [state, formAction, pending] = useActionState(submitQuizAttemptAction, IDLE_ACTION);

  const [answers, setAnswers] = React.useState<Record<string, AnswerValue>>({});
  const [hydrated, setHydrated] = React.useState(false);
  const [secondsLeft, setSecondsLeft] = React.useState<number | null>(attempt.secondsRemaining);
  const [confirmOpen, setConfirmOpen] = React.useState(false);
  const autoSubmitted = React.useRef(false);
  const formRef = React.useRef<HTMLFormElement>(null);

  // Restore after mount: reading storage during render would produce markup
  // that disagrees with the server's, and React would discard it.
  React.useEffect(() => {
    let raw: string | null = null;
    try {
      raw = window.localStorage.getItem(storageKey(attempt.attemptId));
    } catch {
      // Private mode, storage disabled — the quiz still works, just unsaved.
    }
    setAnswers(restoreAnswers(attempt.questions, raw));
    setHydrated(true);
  }, [attempt.attemptId, attempt.questions]);

  // Mirror every change. Guarded on `hydrated` so the empty initial state
  // cannot overwrite a draft that has not been read back yet.
  React.useEffect(() => {
    if (!hydrated) return;
    try {
      window.localStorage.setItem(storageKey(attempt.attemptId), JSON.stringify(answers));
    } catch {
      // Ignored by design.
    }
  }, [answers, attempt.attemptId, hydrated]);

  React.useEffect(() => {
    if (attempt.secondsRemaining === null) return;
    const timer = window.setInterval(() => {
      setSecondsLeft((current) => (current === null ? null : Math.max(0, current - 1)));
    }, 1000);
    return () => window.clearInterval(timer);
  }, [attempt.secondsRemaining]);

  // Time up: hand in whatever has been answered. The server re-checks the
  // deadline, so this is a convenience rather than the enforcement.
  React.useEffect(() => {
    if (secondsLeft !== 0 || autoSubmitted.current || pending) return;
    autoSubmitted.current = true;
    formRef.current?.requestSubmit();
  }, [secondsLeft, pending]);

  // The action redirects on success, so the draft is cleared as soon as the
  // submission starts — there is no post-submit render to hang it on.
  React.useEffect(() => {
    if (!pending) return;
    try {
      window.localStorage.removeItem(storageKey(attempt.attemptId));
    } catch {
      // Ignored by design.
    }
  }, [pending, attempt.attemptId]);

  const answeredCount = attempt.questions.filter((question) => {
    const value = answers[question.id];
    if (value === null || value === undefined) return false;
    if (typeof value === "string") return value.trim().length > 0;
    if (Array.isArray(value)) return value.length > 0;
    return true;
  }).length;

  const total = attempt.questions.length;
  const unanswered = total - answeredCount;
  const progressPercent = total === 0 ? 0 : Math.round((answeredCount / total) * 100);
  const lowTime = secondsLeft !== null && secondsLeft <= 60;
  const errors = state.status === "error" ? state.errors : undefined;

  function setAnswer(questionId: string, value: AnswerValue) {
    setAnswers((current) => ({ ...current, [questionId]: value }));
  }

  function toggleMulti(questionId: string, index: number, checked: boolean) {
    setAnswers((current) => {
      const existing = current[questionId];
      const list = Array.isArray(existing) ? existing : [];
      const next = checked
        ? [...new Set([...list, index])].sort((a, b) => a - b)
        : list.filter((value) => value !== index);
      return { ...current, [questionId]: next };
    });
  }

  return (
    <form ref={formRef} action={formAction} className="space-y-6">
      <input type="hidden" name="attemptId" value={attempt.attemptId} />
      <input type="hidden" name="answers" value={JSON.stringify(answers)} />

      <Card>
        <CardContent className="flex flex-wrap items-center justify-between gap-4 p-5">
          <div className="min-w-0 space-y-1">
            <p className="text-sm font-medium text-primary">
              Percobaan {attempt.attemptNo} · {attempt.courseTitle}
            </p>
            <p className="text-sm text-tertiary">
              {answeredCount} dari {total} soal terjawab
              {unanswered > 0 ? ` · ${unanswered} belum dijawab` : ""}
            </p>
          </div>

          <div className="flex items-center gap-3">
            {secondsLeft === null ? (
              <Badge variant="outline">Tanpa batas waktu</Badge>
            ) : (
              <Badge variant={lowTime ? "danger" : "neutral"}>
                <Clock className="size-3" />
                {formatClock(secondsLeft)}
              </Badge>
            )}
          </div>

          <div className="w-full">
            <Progress value={progressPercent} tone={progressPercent === 100 ? "success" : "brand"} />
          </div>
        </CardContent>
      </Card>

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

      {lowTime ? (
        <Alert tone="warning" title="Waktu hampir habis">
          Jawabanmu akan dikumpulkan otomatis saat waktu habis.
        </Alert>
      ) : null}

      {attempt.questions.map((question, index) => (
        <QuestionCard
          key={question.id}
          question={question}
          number={index + 1}
          value={answers[question.id] ?? null}
          error={errors?.[question.id]}
          disabled={pending}
          onChange={(value) => setAnswer(question.id, value)}
          onToggleMulti={(optionIndex, checked) =>
            toggleMulti(question.id, optionIndex, checked)
          }
        />
      ))}

      <Card>
        <CardContent className="flex flex-wrap items-center justify-between gap-4 p-5">
          <div className="text-sm text-tertiary">
            {unanswered > 0 ? (
              <span>
                Masih ada <strong className="text-primary">{unanswered} soal</strong> yang belum
                dijawab.
              </span>
            ) : (
              <span className="inline-flex items-center gap-2 text-success">
                <CheckCircle2 className="size-4" />
                Semua soal sudah dijawab.
              </span>
            )}
          </div>

          <div className="flex flex-wrap gap-2">
            <Button
              type="button"
              disabled={pending}
              onClick={() => setConfirmOpen(true)}
            >
              <Send className="size-4" />
              {pending ? "Mengumpulkan…" : "Kumpulkan jawaban"}
            </Button>
          </div>
        </CardContent>
      </Card>

      <Dialog open={confirmOpen} onOpenChange={setConfirmOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Kumpulkan jawaban sekarang?</DialogTitle>
            <DialogDescription>
              {unanswered > 0
                ? `Ada ${unanswered} soal yang belum dijawab dan akan dihitung salah. Jawaban tidak dapat diubah setelah dikumpulkan.`
                : "Jawaban tidak dapat diubah setelah dikumpulkan."}
            </DialogDescription>
          </DialogHeader>
          <div className="flex justify-end gap-2">
            <DialogClose asChild>
              <Button type="button" variant="secondary">
                Periksa lagi
              </Button>
            </DialogClose>
            <Button
              type="button"
              disabled={pending}
              onClick={() => {
                setConfirmOpen(false);
                formRef.current?.requestSubmit();
              }}
            >
              Ya, kumpulkan
            </Button>
          </div>
        </DialogContent>
      </Dialog>
    </form>
  );
}

function QuestionCard({
  question,
  number,
  value,
  error,
  disabled,
  onChange,
  onToggleMulti,
}: {
  question: StudentQuestion;
  number: number;
  value: AnswerValue;
  error?: string;
  disabled: boolean;
  onChange: (value: AnswerValue) => void;
  onToggleMulti: (optionIndex: number, checked: boolean) => void;
}) {
  const selected = Array.isArray(value) ? value : [];

  return (
    <Card>
      <CardHeader>
        <div className="flex flex-wrap items-start justify-between gap-3">
          <CardTitle className="flex-1">
            <span className="mr-2 text-tertiary">{number}.</span>
            {question.prompt}
          </CardTitle>
          <Badge variant="neutral">{question.points} poin</Badge>
        </div>
        <p className="text-xs text-tertiary">{TYPE_LABEL[question.type]}</p>
      </CardHeader>

      <CardContent className="space-y-2">
        {question.type === "MULTIPLE_CHOICE" || question.type === "TRUE_FALSE" ? (
          question.options.map((option, index) => (
            <label
              key={index}
              className="flex cursor-pointer items-center gap-3 rounded-md border border-subtle p-3 text-sm hover:bg-sunken has-[:checked]:border-brand-600 has-[:checked]:bg-sunken"
            >
              <input
                type="radio"
                name={`q-${question.id}`}
                className="size-4 accent-current"
                checked={value === index}
                disabled={disabled}
                onChange={() => onChange(index)}
              />
              <span className="text-secondary">{option}</span>
            </label>
          ))
        ) : null}

        {question.type === "MULTI_SELECT" ? (
          question.options.map((option, index) => (
            <label
              key={index}
              className="flex cursor-pointer items-center gap-3 rounded-md border border-subtle p-3 text-sm hover:bg-sunken has-[:checked]:border-brand-600 has-[:checked]:bg-sunken"
            >
              <Checkbox
                checked={selected.includes(index)}
                disabled={disabled}
                onCheckedChange={(checked) => onToggleMulti(index, checked === true)}
              />
              <span className="text-secondary">{option}</span>
            </label>
          ))
        ) : null}

        {question.type === "SHORT_ANSWER" ? (
          <input
            type="text"
            className="h-10 w-full rounded-md border border-input bg-surface-1 px-3 text-sm text-primary outline-none focus:border-primary"
            placeholder="Tulis jawabanmu"
            value={typeof value === "string" ? value : ""}
            disabled={disabled}
            onChange={(event) => onChange(event.target.value)}
          />
        ) : null}

        {question.type === "CODE" ? (
          <Textarea
            rows={8}
            className="font-mono text-sm"
            placeholder="Tulis kodemu di sini"
            value={typeof value === "string" ? value : ""}
            disabled={disabled}
            onChange={(event) => onChange(event.target.value)}
          />
        ) : null}

        {question.type === "CODE" ? (
          <p className="inline-flex items-center gap-2 text-xs text-tertiary">
            <CircleHelp className="size-3" />
            Soal kode dinilai manual oleh pengajar.
          </p>
        ) : null}

        {error ? <p className="text-xs text-danger-500">{error}</p> : null}
      </CardContent>
    </Card>
  );
}

/**
 * Shown when a timed attempt expired before the student came back.
 *
 * Nothing can be recovered — the answers only ever existed in their browser —
 * so the honest move is to close the attempt rather than leave it open
 * forever. The score is recomputed from an empty paper.
 */
export function ExpiredAttemptNotice({ attempt }: { attempt: ActiveAttempt }) {
  const [state, formAction, pending] = useActionState(expireQuizAttemptAction, IDLE_ACTION);

  return (
    <Card>
      <CardContent className="space-y-4 p-6">
        <div className="flex items-start gap-3">
          <AlertTriangle className="mt-0.5 size-5 text-warning" />
          <div className="space-y-1">
            <p className="font-medium text-primary">Waktu pengerjaan sudah habis</p>
            <p className="text-sm text-secondary">
              Batas waktu {attempt.timeLimitMinutes} menit untuk percobaan ini sudah terlampaui.
              Jawaban yang tersimpan di peramban tidak dapat dipulihkan, jadi percobaan ini akan
              ditutup dengan nilai 0. Kamu masih bisa memakai sisa kesempatan bila tersedia.
            </p>
          </div>
        </div>

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

        <form action={formAction}>
          <input type="hidden" name="attemptId" value={attempt.attemptId} />
          <Button type="submit" disabled={pending}>
            {pending ? "Menutup…" : "Tutup percobaan"}
          </Button>
        </form>
      </CardContent>
    </Card>
  );
}
