"use client";

import * as React from "react";
import { useActionState } from "react";
import { Save } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { gradeQuizAnswerAction } from "@/actions/quizzes";
import { IDLE_ACTION } from "@/lib/action-state";
import {
  BLOCKED_NUMERIC_KEYS,
  isValidScoreInput,
  normaliseInteger,
} from "@/lib/numeric-input";

/**
 * Marks one hand-graded answer.
 *
 * The server refuses this on an auto-graded question, so the control is only
 * rendered where it is meaningful. Success and failure are both reported inline
 * because a teacher marking a class works through many of these in a row and
 * should not have to leave the page to see whether each one saved.
 */
export function GradeAnswerForm({
  answerId,
  maxPoints,
  currentPoints,
}: {
  answerId: string;
  maxPoints: number;
  currentPoints: number;
}) {
  const [state, formAction, pending] = useActionState(gradeQuizAnswerAction, IDLE_ACTION);
  const [points, setPoints] = React.useState(String(currentPoints));
  const valid = isValidScoreInput(points, maxPoints);

  return (
    <form action={formAction} className="flex flex-wrap items-center gap-2">
      <input type="hidden" name="answerId" value={answerId} />

      <Input
        name="points"
        // text + inputMode numeric: the server rounds to a whole point, so a
        // decimal here would be silently changed on save. Refusing the
        // keystroke is clearer than accepting it and rounding behind the
        // teacher's back.
        type="text"
        inputMode="numeric"
        autoComplete="off"
        pattern="[0-9]*"
        maxLength={String(maxPoints).length}
        value={points}
        onChange={(event) => {
          const next = normaliseInteger(event.target.value, maxPoints);
          if (next !== null) setPoints(next);
        }}
        onKeyDown={(event) => {
          if (BLOCKED_NUMERIC_KEYS.has(event.key)) event.preventDefault();
        }}
        onPaste={(event) => {
          event.preventDefault();
          const next = normaliseInteger(event.clipboardData.getData("text"), maxPoints);
          if (next !== null) setPoints(next);
        }}
        className="h-9 w-20"
        aria-label={`Poin (maksimal ${maxPoints})`}
      />

      <span className="text-xs text-tertiary">/ {maxPoints} poin</span>

      <Button type="submit" size="sm" variant="secondary" disabled={pending || !valid}>
        <Save className="size-3.5" />
        {pending ? "Menyimpan…" : "Simpan nilai"}
      </Button>

      {state.status === "success" ? (
        <span className="text-xs text-success-600">{state.message}</span>
      ) : null}
      {state.status === "error" ? (
        <span className="text-xs text-danger-500">{state.message}</span>
      ) : null}
    </form>
  );
}
