"use client";

import * as React from "react";
import { useActionState } from "react";
import { Save, Send, TriangleAlert } from "lucide-react";
import { Alert } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Field, Textarea } from "@/components/ui/input";
import { gradeSubmissionAction } from "@/actions/assignments";
import { IDLE_ACTION } from "@/lib/action-state";
import { scoreToneClass } from "@/lib/labels";
import { BLOCKED_NUMERIC_KEYS, normaliseInteger } from "@/lib/numeric-input";

const QUICK_FEEDBACK = [
  "Kerja bagus, pertahankan!",
  "Perhatikan kembali bagian yang belum tepat.",
  "Sudah benar, tambahkan penjelasan agar lebih lengkap.",
  "Periksa kembali logika penyelesaiannya.",
];

/**
 * Grading form.
 *
 * Shows a live percentage as the teacher types and warns when the score exceeds
…
 */
export function GradingForm({
  submissionId,
  maxScore,
  initialScore,
  initialFeedback,
}: {
  submissionId: string;
  maxScore: number;
  initialScore: number | null;
  initialFeedback: string | null;
}) {
  const [state, formAction, pending] = useActionState(gradeSubmissionAction, IDLE_ACTION);
  const [score, setScore] = React.useState(initialScore === null ? "" : String(initialScore));
  const [feedback, setFeedback] = React.useState(initialFeedback ?? "");

  const numeric = Number(score);
  const valid = score.trim() !== "" && Number.isFinite(numeric) && numeric >= 0 && numeric <= maxScore;
  const percent = valid ? (numeric / maxScore) * 100 : null;
  const errors = state.status === "error" ? state.errors : undefined;

  return (
    <Card>
      <CardHeader>
        <CardTitle>Beri Nilai</CardTitle>
      </CardHeader>
      <CardContent>
        <form action={formAction} className="space-y-4">
          <input type="hidden" name="submissionId" value={submissionId} />

          {state.status === "error" && state.message ? (
            <Alert tone="danger" icon={<TriangleAlert className="size-4" />}>
              {state.message}
            </Alert>
          ) : null}
          {state.status === "success" && state.message ? (
            <Alert tone="success">{state.message}</Alert>
          ) : null}

          <Field
            label={`Nilai (0–${maxScore})`}
            htmlFor="grade-score"
            required
            error={errors?.score}
            hint={
              percent === null
                ? undefined
                : `Setara ${percent.toFixed(1)}% dari nilai maksimal.`
            }
          >
            <div className="flex items-center gap-3">
              <input
                id="grade-score"
                name="score"
                // text + inputMode numeric: keeps the digit keypad on touch
                // devices while letting us reject stray characters outright.
                type="text"
                inputMode="numeric"
                autoComplete="off"
                pattern="[0-9]*"
                maxLength={String(maxScore).length}
                required
                value={score}
                onChange={(event) => {
                  const next = normaliseInteger(event.target.value, maxScore);
                  // null means the edit would exceed the ceiling; keep the old
                  // value rather than letting the field go blank.
                  if (next !== null) setScore(next);
                }}
                onKeyDown={(event) => {
                  // Block the characters a number input would have allowed and
                  // the browser would then reject as invalid.
                  if (BLOCKED_NUMERIC_KEYS.has(event.key)) {
                    event.preventDefault();
                  }
                }}
                onPaste={(event) => {
                  event.preventDefault();
                  const pasted = event.clipboardData.getData("text");
                  const next = normaliseInteger(pasted, maxScore);
                  if (next !== null) setScore(next);
                }}
                className="h-10 w-28 border border-line bg-surface px-3 text-sm text-primary focus:border-brand-600 focus:outline-none focus:ring-1 focus:ring-brand-600/30"
              />
              {percent !== null ? (
                <span className={`text-lg font-bold tabular-nums ${scoreToneClass(percent)}`}>
                  {percent.toFixed(0)}%
                </span>
              ) : null}
            </div>
          </Field>

          <Field label="Umpan Balik" htmlFor="grade-feedback" error={errors?.feedback}>
            <Textarea
              id="grade-feedback"
              name="feedback"
              rows={5}
              value={feedback}
              onChange={(event) => setFeedback(event.target.value)}
              placeholder="Tuliskan catatan untuk siswa…"
            />
          </Field>

          <div className="flex flex-wrap gap-2">
            {QUICK_FEEDBACK.map((preset) => (
              <Button
                key={preset}
                type="button"
                variant="subtle"
                size="sm"
                onClick={() => setFeedback(preset)}
              >
                {preset}
              </Button>
            ))}
          </div>

          <label className="flex items-center gap-2 text-sm text-primary">
            <input type="checkbox" name="returnToStudent" defaultChecked />
            Kembalikan ke siswa dan kirim notifikasi
          </label>

          <div className="flex gap-2">
            <Button type="submit" loading={pending} disabled={!valid}>
              <Save className="size-4" />
              Simpan Penilaian
            </Button>
            <Button
              type="button"
              variant="secondary"
              onClick={() => {
                setScore(String(maxScore));
              }}
            >
              <Send className="size-4" />
              Nilai Penuh
            </Button>
          </div>
        </form>
      </CardContent>
    </Card>
  );
}
