"use client";

import { useActionState, useState } from "react";
import { submitAdmission } from "@/app/actions/forms";
import type { ActionState } from "@/app/lib/definitions";

const programs = [
  "Early Years (Pre-Primary)",
  "Lower Primary (Grade 1 - 3)",
  "Upper Primary (Grade 4 - 6)",
  "Junior Secondary (Grade 7 - 9)",
  "IGCSE",
  "A-Level",
  "Holiday & Revision",
];

const gradeLevels = [
  "Pre-Primary",
  "Grade 1",
  "Grade 2",
  "Grade 3",
  "Grade 4",
  "Grade 5",
  "Grade 6",
  "Grade 7",
  "Grade 8",
  "Grade 9",
  "IGCSE",
  "A-Level",
];

const initialState: ActionState = {};

export default function AdmissionsForm() {
  const [formKey, setFormKey] = useState(0);

  return (
    <AdmissionsFormInner
      key={formKey}
      onReset={() => {
        setFormKey((k) => k + 1);
        window.scrollTo({ top: 0, behavior: "smooth" });
      }}
    />
  );
}

function AdmissionsFormInner({ onReset }: { onReset: () => void }) {
  const [state, action, pending] = useActionState(
    submitAdmission,
    initialState,
  );

  if (state?.success) {
    return (
      <div className="rounded-2xl border border-[#e9eefc] bg-white p-6 sm:p-10 md:p-14 text-center">
        <div className="mx-auto flex h-14 w-14 items-center justify-center rounded-full bg-[#1f3fb8]/10">
          <svg
            className="h-7 w-7 text-[#1f3fb8]"
            fill="none"
            viewBox="0 0 24 24"
            stroke="currentColor"
            strokeWidth={2.5}
            aria-hidden="true"
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              d="M5 13l4 4L19 7"
            />
          </svg>
        </div>
        <h3 className="mt-5 text-2xl font-bold tracking-tight text-[#132b87]">
          Application received
        </h3>
        <p className="mt-3 text-[#5a688d] leading-relaxed max-w-md mx-auto">
          Thank you for applying. Our admissions team will reach out within 1 -
          2 working days to schedule a placement meeting.
        </p>
        <button
          type="button"
          onClick={onReset}
          className="mt-7 text-sm font-semibold text-[#1f3fb8] hover:text-[#18339a] transition"
        >
          Submit another application →
        </button>
      </div>
    );
  }

  return (
    <form
      action={action}
      className="rounded-2xl border border-[#e9eefc] bg-white p-5 sm:p-6 md:p-10 relative"
    >
      <div
        aria-hidden="true"
        className="absolute -left-[9999px] h-0 w-0 overflow-hidden"
      >
        <label>
          Website
          <input type="text" name="website" tabIndex={-1} autoComplete="off" />
        </label>
      </div>

      <section className="pb-8 mb-8 md:pb-10 md:mb-10 border-b border-[#eef1fb]">
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-8 lg:gap-10 divide-y divide-[#eef1fb] lg:divide-y-0">
          <div className="pt-0">
            <SectionHeader title="Student" caption="About the learner" />
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-x-5 gap-y-5">
              <Field
                label="First name"
                required
                error={state?.errors?.studentFirstName?.[0]}
              >
                <input
                  type="text"
                  name="studentFirstName"
                  required
                  className={inputCls}
                  placeholder="Amani"
                />
              </Field>
              <Field
                label="Last name"
                required
                error={state?.errors?.studentLastName?.[0]}
              >
                <input
                  type="text"
                  name="studentLastName"
                  required
                  className={inputCls}
                  placeholder="Otieno"
                />
              </Field>
              <Field
                label="Date of birth"
                required
                error={state?.errors?.studentDob?.[0]}
              >
                <input
                  type="date"
                  name="studentDob"
                  required
                  className={inputCls}
                />
              </Field>
              <Field label="Gender" error={state?.errors?.studentGender?.[0]}>
                <select
                  name="studentGender"
                  className={inputCls}
                  defaultValue=""
                >
                  <option value="">Select</option>
                  <option value="female">Female</option>
                  <option value="male">Male</option>
                  <option value="prefer-not">Prefer not to say</option>
                </select>
              </Field>
              <Field
                label="Current / previous school"
                error={state?.errors?.currentSchool?.[0]}
              >
                <input
                  type="text"
                  name="currentSchool"
                  className={inputCls}
                  placeholder="Name of the school"
                />
              </Field>
              <Field
                label="Current grade"
                required
                error={state?.errors?.gradeLevel?.[0]}
              >
                <select
                  name="gradeLevel"
                  required
                  className={inputCls}
                  defaultValue=""
                >
                  <option value="">Select grade</option>
                  {gradeLevels.map((g) => (
                    <option key={g} value={g}>
                      {g}
                    </option>
                  ))}
                </select>
              </Field>
            </div>
          </div>

          <div className="pt-8 lg:pt-0 lg:border-l lg:border-[#eef1fb] lg:pl-10">
            <SectionHeader title="Program" caption="Pathway and start date" />
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-x-5 gap-y-5">
              <Field
                label="Program of interest"
                required
                error={state?.errors?.program?.[0]}
              >
                <select
                  name="program"
                  required
                  className={inputCls}
                  defaultValue=""
                >
                  <option value="">Select a program</option>
                  {programs.map((p) => (
                    <option key={p} value={p}>
                      {p}
                    </option>
                  ))}
                </select>
              </Field>
              <Field
                label="Preferred start date"
                required
                error={state?.errors?.startDate?.[0]}
              >
                <input
                  type="date"
                  name="startDate"
                  required
                  className={inputCls}
                />
              </Field>
            </div>
          </div>

          <div className="pt-8 lg:pt-0 lg:border-l lg:border-[#eef1fb] lg:pl-10">
            <SectionHeader
              title="Parent / Guardian"
              caption="Primary contact"
            />
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-x-5 gap-y-5">
              <Field
                label="Full name"
                required
                error={state?.errors?.parentName?.[0]}
              >
                <input
                  type="text"
                  name="parentName"
                  required
                  className={inputCls}
                  placeholder="Parent or guardian name"
                />
              </Field>
              <Field
                label="Relationship"
                required
                error={state?.errors?.relationship?.[0]}
              >
                <select
                  name="relationship"
                  required
                  className={inputCls}
                  defaultValue=""
                >
                  <option value="">Select</option>
                  <option>Mother</option>
                  <option>Father</option>
                  <option>Guardian</option>
                  <option>Other</option>
                </select>
              </Field>
              <Field label="Email" required error={state?.errors?.email?.[0]}>
                <input
                  type="email"
                  name="email"
                  required
                  className={inputCls}
                  placeholder="you@example.com"
                />
              </Field>
              <Field label="Phone" required error={state?.errors?.phone?.[0]}>
                <input
                  type="tel"
                  name="phone"
                  required
                  className={inputCls}
                  placeholder="+254 7XX XXX XXX"
                />
              </Field>
            </div>
          </div>
        </div>
      </section>

      <section>
        <Field label="Notes (optional)" error={state?.errors?.notes?.[0]}>
          <textarea
            name="notes"
            rows={2}
            className={`${inputCls} resize-y min-h-16`}
            placeholder="Special learning needs, interests, questions..."
          />
        </Field>

        <label className="mt-6 flex items-start gap-3 cursor-pointer select-none">
          <input
            type="checkbox"
            name="consent"
            value="true"
            className="mt-1 h-4 w-4 accent-[#1f3fb8]"
          />
          <span className="text-sm text-[#5a688d] leading-relaxed">
            I confirm the information provided is accurate and consent to Vido
            International Home School contacting me about this application.
          </span>
        </label>
        {state?.errors?.consent?.[0] && (
          <p className="mt-2 text-xs text-red-600" role="alert">
            {state.errors.consent[0]}
          </p>
        )}
      </section>

      {state?.message && !state.success && (
        <p className="mt-4 text-sm text-red-600" role="alert">
          {state.message}
        </p>
      )}

      <div className="mt-8 md:mt-10 flex flex-col-reverse sm:flex-row sm:items-center sm:justify-between gap-4">
        <p className="text-xs text-[#5a688d]">
          A reply usually arrives within 1 - 2 working days.
        </p>
        <button
          type="submit"
          disabled={pending}
          className="w-full sm:w-auto inline-flex items-center justify-center gap-2 px-8 py-3 bg-[#1f3fb8] text-white text-sm font-semibold rounded-full hover:bg-[#18339a] transition disabled:opacity-60"
        >
          {pending ? "Submitting..." : "Submit application"}
          <span aria-hidden="true">→</span>
        </button>
      </div>
    </form>
  );
}

const inputCls =
  "w-full rounded-lg border border-[#e3e8f5] bg-white px-3.5 py-2.5 text-sm text-[#132b87] placeholder:text-[#a5b0cc] focus:outline-none focus:border-[#1f3fb8] focus:ring-2 focus:ring-[#1f3fb8]/15 transition";

function Field({
  label,
  required,
  error,
  children,
}: {
  label: string;
  required?: boolean;
  error?: string;
  children: React.ReactNode;
}) {
  return (
    <label className="block">
      <span className="block text-xs font-medium text-[#5a688d] mb-1.5">
        {label}
        {required && <span className="text-[#1f3fb8]"> *</span>}
      </span>
      {children}
      {error && (
        <span className="mt-1 block text-xs text-red-600" role="alert">
          {error}
        </span>
      )}
    </label>
  );
}

function SectionHeader({ title, caption }: { title: string; caption: string }) {
  return (
    <div className="mb-6">
      <h3 className="text-base font-semibold text-[#132b87]">{title}</h3>
      <p className="text-xs text-[#9aa7c4] mt-0.5">{caption}</p>
    </div>
  );
}
