"use client";

import { useActionState, useEffect } from "react";
import { useFormStatus } from "react-dom";
import { Save } from "lucide-react";
import { updateStudentAction } from "@/app/actions/students";
import type { ActionResult } from "@/app/actions/shared";
import { buttonClass, Field, inputClass } from "@/components/ui";
import { useToast } from "@/components/toast";
import { formatDateTime } from "@/components/status";
import type { Student } from "@/types";

const initialState: ActionResult = { ok: false, message: null };

function SaveButton({ disabled }: { disabled: boolean }) {
  const { pending } = useFormStatus();
  return (
    <button type="submit" className={buttonClass("primary")} disabled={pending || disabled}>
      <Save className="h-4 w-4" aria-hidden />
      {pending ? "Saving…" : "Save profile"}
    </button>
  );
}

export function StudentProfileForm({
  student,
  readOnly,
  canArchive,
  updatedByName,
}: {
  student: Student;
  readOnly: boolean;
  canArchive: boolean;
  updatedByName: string | null;
}) {
  const [state, formAction] = useActionState<ActionResult, FormData>(updateStudentAction, initialState);
  const { toast } = useToast();

  useEffect(() => {
    if (!state.message) return;
    toast({ tone: state.ok ? "success" : "error", title: state.message });
  }, [state, toast]);

  const error = (field: string) => state.fieldErrors?.[field] ?? null;

  return (
    <form action={formAction} className="space-y-6">
      <input type="hidden" name="student_id" value={student.id} />

      <fieldset disabled={readOnly} className="space-y-6">
        <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
          <Field label="Student number" htmlFor="student_number" required error={error("student_number")}>
            <input
              id="student_number"
              name="student_number"
              defaultValue={student.student_number}
              className={`${inputClass} tabular`}
              required
              maxLength={50}
            />
          </Field>
          <Field label="Last name" htmlFor="last_name" required error={error("last_name")}>
            <input id="last_name" name="last_name" defaultValue={student.last_name} className={inputClass} required />
          </Field>
          <Field label="First name" htmlFor="first_name" required error={error("first_name")}>
            <input id="first_name" name="first_name" defaultValue={student.first_name} className={inputClass} required />
          </Field>
          <Field label="Middle name" htmlFor="middle_name" error={error("middle_name")}>
            <input id="middle_name" name="middle_name" defaultValue={student.middle_name ?? ""} className={inputClass} />
          </Field>
          <Field label="Suffix" htmlFor="suffix" error={error("suffix")} hint="e.g. Jr., III">
            <input id="suffix" name="suffix" defaultValue={student.suffix ?? ""} className={inputClass} />
          </Field>
        </div>

        <div>
          <h3 className="mb-3 text-[11px] font-semibold uppercase tracking-wider text-ink-500">
            Pre-medical background
          </h3>
          <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
            <Field label="Pre-med course" htmlFor="premed_course" error={error("premed_course")}>
              <input
                id="premed_course"
                name="premed_course"
                defaultValue={student.premed_course ?? ""}
                className={inputClass}
                placeholder="e.g. BS Biology"
              />
            </Field>
            <Field label="Pre-med school" htmlFor="premed_school" error={error("premed_school")}>
              <input
                id="premed_school"
                name="premed_school"
                defaultValue={student.premed_school ?? ""}
                className={inputClass}
              />
            </Field>
            <Field label="Year graduated" htmlFor="graduation_year" error={error("graduation_year")}>
              <input
                id="graduation_year"
                name="graduation_year"
                defaultValue={student.graduation_year ?? ""}
                className={`${inputClass} tabular`}
                inputMode="numeric"
                placeholder="YYYY"
              />
            </Field>
            <Field label="GWA" htmlFor="gwa" error={error("gwa")} hint="Stored as text to match your grading format.">
              <input id="gwa" name="gwa" defaultValue={student.gwa ?? ""} className={`${inputClass} tabular`} />
            </Field>
            <Field label="NMAT score" htmlFor="nmat_score" error={error("nmat_score")}>
              <input
                id="nmat_score"
                name="nmat_score"
                defaultValue={student.nmat_score ?? ""}
                className={`${inputClass} tabular`}
                inputMode="decimal"
              />
            </Field>
            <Field label="Year NMAT taken" htmlFor="nmat_year" error={error("nmat_year")}>
              <input
                id="nmat_year"
                name="nmat_year"
                defaultValue={student.nmat_year ?? ""}
                className={`${inputClass} tabular`}
                inputMode="numeric"
                placeholder="YYYY"
              />
            </Field>
          </div>
        </div>

        <Field label="Notes" htmlFor="notes" error={error("notes")}>
          <textarea
            id="notes"
            name="notes"
            defaultValue={student.notes ?? ""}
            rows={3}
            className={inputClass}
            placeholder="Internal notes about this student record."
          />
        </Field>

        <label className="flex items-start gap-2.5">
          <input
            type="checkbox"
            name="active"
            defaultChecked={student.active === 1}
            disabled={!canArchive || readOnly}
            className="mt-0.5 h-4 w-4 rounded border-ink-300 text-brand-600 focus:ring-brand-500 disabled:opacity-50"
          />
          <span className="text-[13px]">
            <span className="font-medium text-ink-800">Active student</span>
            <span className="block text-ink-500">
              {canArchive
                ? "Clear this to archive the record. Archived students are excluded from reports by default."
                : "Only an administrator can archive or restore a student."}
            </span>
          </span>
        </label>
      </fieldset>

      {!readOnly ? (
        <div className="flex flex-wrap items-center justify-between gap-3 border-t border-ink-200 pt-4">
          <p className="text-[12px] text-ink-500">
            Last updated {formatDateTime(student.updated_at)}
            {updatedByName ? ` by ${updatedByName}` : ""}
          </p>
          <SaveButton disabled={readOnly} />
        </div>
      ) : (
        <p className="border-t border-ink-200 pt-4 text-[12px] text-ink-500">
          Last updated {formatDateTime(student.updated_at)}
          {updatedByName ? ` by ${updatedByName}` : ""}
        </p>
      )}
    </form>
  );
}
