"use client";

import { useEffect, useRef, useState } from "react";
import { Loader2, X } from "lucide-react";
import { updateAssessmentAction, type AssessmentSaveData } from "@/app/actions/assessment";
import { buttonClass, Callout, Field, inputClass, selectClass } from "@/components/ui";
import { useToast } from "@/components/toast";
import { ASSESSMENT_STATUS_LABELS } from "@/components/status";
import { ASSESSMENT_STATUSES, type AssessmentStatus } from "@/types";
import type { AssessmentRowView } from "@/components/students/assessment-workspace";

/**
 * Transfer / equivalency credit (SPEC 18).
 *
 * A transferred subject satisfies a specific MMC CAST curriculum requirement;
 * the requirement's own units are what count. An academic administrator may
 * approve a different credited-unit value, but never one larger than the
 * requirement itself.
 */
export function EquivalencyDialog({
  studentId,
  row,
  canApprove,
  onClose,
  onSaved,
}: {
  studentId: string;
  row: AssessmentRowView;
  canApprove: boolean;
  onClose: () => void;
  onSaved: (data: AssessmentSaveData) => void;
}) {
  const dialogRef = useRef<HTMLDialogElement>(null);
  const { toast } = useToast();
  const [pending, setPending] = useState(false);
  const [errors, setErrors] = useState<Record<string, string>>({});

  useEffect(() => {
    dialogRef.current?.showModal();
  }, []);

  const submit = async (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    setPending(true);
    setErrors({});
    const formData = new FormData(event.currentTarget);
    formData.set("student_id", studentId);
    formData.set("curriculum_course_id", row.courseId);

    const result = await updateAssessmentAction({ ok: false, message: null }, formData);
    setPending(false);

    if (result.ok && result.data) {
      toast({ tone: "success", title: `Equivalency saved for ${row.courseCode}.` });
      onSaved(result.data);
    } else {
      setErrors(result.fieldErrors ?? {});
      toast({ tone: "error", title: result.message ?? "The equivalency could not be saved." });
    }
  };

  return (
    <dialog
      ref={dialogRef}
      onClose={onClose}
      onCancel={onClose}
      className="w-[min(38rem,calc(100vw-2rem))] rounded-xl border border-ink-200 p-0 shadow-xl backdrop:bg-ink-900/40"
      aria-labelledby="equivalency-title"
    >
      <form onSubmit={submit}>
        <div className="flex items-start justify-between gap-3 border-b border-ink-200 px-5 py-4">
          <div>
            <h2 id="equivalency-title" className="text-sm font-semibold text-ink-900">
              Transfer / equivalency credit
            </h2>
            <p className="mt-0.5 text-[13px] text-ink-500">
              {row.courseCode} — {row.courseTitle} ({row.units} units)
            </p>
          </div>
          <button
            type="button"
            onClick={onClose}
            className="rounded p-1 text-ink-400 hover:bg-ink-100 hover:text-ink-700"
            aria-label="Close"
          >
            <X className="h-4 w-4" />
          </button>
        </div>

        <div className="space-y-4 px-5 py-4">
          <Callout tone="info">
            A transferred subject only counts once it is mapped to this MMC CAST curriculum requirement. The
            requirement&apos;s own {row.units} units are what count toward completion — the source course&apos;s units
            are recorded for reference only.
          </Callout>

          <div className="grid gap-4 sm:grid-cols-2">
            <Field label="Source school" htmlFor="equivalent_source_school">
              <input
                id="equivalent_source_school"
                name="equivalent_source_school"
                defaultValue={row.equivalentSourceSchool}
                className={inputClass}
                placeholder="e.g. Previous medical school"
              />
            </Field>
            <Field label="Source course code" htmlFor="equivalent_course_code">
              <input
                id="equivalent_course_code"
                name="equivalent_course_code"
                defaultValue={row.equivalentCourseCode}
                className={inputClass}
              />
            </Field>
            <Field label="Source course title" htmlFor="equivalent_course_title" className="sm:col-span-2">
              <input
                id="equivalent_course_title"
                name="equivalent_course_title"
                defaultValue={row.equivalentCourseTitle}
                className={inputClass}
              />
            </Field>
            <Field label="Source units" htmlFor="equivalent_source_units" error={errors.equivalent_source_units}>
              <input
                id="equivalent_source_units"
                name="equivalent_source_units"
                defaultValue={row.equivalentSourceUnits ?? ""}
                className={`${inputClass} tabular`}
                inputMode="decimal"
              />
            </Field>
            <Field label="Credit status" htmlFor="status" required>
              <select id="status" name="status" defaultValue={row.status} className={selectClass}>
                {ASSESSMENT_STATUSES.map((status) => (
                  <option key={status} value={status}>
                    {ASSESSMENT_STATUS_LABELS[status as AssessmentStatus]}
                  </option>
                ))}
              </select>
            </Field>
          </div>

          <Field
            label="Approved credited units (optional)"
            htmlFor="approved_credited_units_override"
            error={errors.approved_credited_units_override}
            hint={
              canApprove
                ? `Leave blank to credit the full ${row.units} requirement units. Cannot exceed ${row.units}.`
                : "Only an academic administrator can approve a special credited-unit value."
            }
          >
            <input
              id="approved_credited_units_override"
              name="approved_credited_units_override"
              defaultValue={row.approvedCreditedUnitsOverride ?? ""}
              disabled={!canApprove}
              className={`${inputClass} tabular`}
              inputMode="decimal"
              max={row.units}
            />
          </Field>

          <Field label="Approval remarks" htmlFor="remarks">
            <textarea id="remarks" name="remarks" rows={2} defaultValue={row.remarks} className={inputClass} />
          </Field>

          <input type="hidden" name="grade_raw" value={row.gradeRaw ?? ""} />
        </div>

        <div className="flex justify-end gap-2 border-t border-ink-200 bg-ink-50 px-5 py-3">
          <button type="button" onClick={onClose} className={buttonClass("secondary", "sm")}>
            Cancel
          </button>
          <button type="submit" className={buttonClass("primary", "sm")} disabled={pending}>
            {pending ? <Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden /> : null}
            Save equivalency
          </button>
        </div>
      </form>
    </dialog>
  );
}
