"use client";

import { useState } from "react";

type FormState = {
  studentFirstName: string;
  studentLastName: string;
  studentDob: string;
  studentGender: string;
  currentSchool: string;
  gradeLevel: string;
  program: string;
  startDate: string;
  parentName: string;
  relationship: string;
  email: string;
  phone: string;
  notes: string;
  consent: boolean;
};

const initialState: FormState = {
  studentFirstName: "",
  studentLastName: "",
  studentDob: "",
  studentGender: "",
  currentSchool: "",
  gradeLevel: "",
  program: "",
  startDate: "",
  parentName: "",
  relationship: "",
  email: "",
  phone: "",
  notes: "",
  consent: false,
};

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",
];

export default function AdmissionsForm() {
  const [form, setForm] = useState<FormState>(initialState);
  const [submitted, setSubmitted] = useState(false);
  const [error, setError] = useState<string | null>(null);

  function update<K extends keyof FormState>(key: K, value: FormState[K]) {
    setForm((prev) => ({ ...prev, [key]: value }));
  }

  function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setError(null);

    if (!form.consent) {
      setError("Please confirm the information and consent to proceed.");
      return;
    }

    setSubmitted(true);
    setForm(initialState);
    window.scrollTo({ top: 0, behavior: "smooth" });
  }

  if (submitted) {
    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={() => setSubmitted(false)}
          className="mt-7 text-sm font-semibold text-[#1f3fb8] hover:text-[#18339a] transition"
        >
          Submit another application →
        </button>
      </div>
    );
  }

  return (
    <form
      onSubmit={handleSubmit}
      className="rounded-2xl border border-[#e9eefc] bg-white p-5 sm:p-6 md:p-10"
      noValidate
    >
      <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">
          {/* Student */}
          <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>
                <input
                  type="text"
                  required
                  value={form.studentFirstName}
                  onChange={(e) => update("studentFirstName", e.target.value)}
                  className={inputCls}
                  placeholder="Amani"
                />
              </Field>
              <Field label="Last name" required>
                <input
                  type="text"
                  required
                  value={form.studentLastName}
                  onChange={(e) => update("studentLastName", e.target.value)}
                  className={inputCls}
                  placeholder="Otieno"
                />
              </Field>
              <Field label="Date of birth" required>
                <input
                  type="date"
                  required
                  value={form.studentDob}
                  onChange={(e) => update("studentDob", e.target.value)}
                  className={inputCls}
                />
              </Field>
              <Field label="Gender">
                <select
                  value={form.studentGender}
                  onChange={(e) => update("studentGender", e.target.value)}
                  className={inputCls}
                >
                  <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">
                <input
                  type="text"
                  value={form.currentSchool}
                  onChange={(e) => update("currentSchool", e.target.value)}
                  className={inputCls}
                  placeholder="Name of the school"
                />
              </Field>
              <Field label="Current grade" required>
                <select
                  required
                  value={form.gradeLevel}
                  onChange={(e) => update("gradeLevel", e.target.value)}
                  className={inputCls}
                >
                  <option value="">Select grade</option>
                  {gradeLevels.map((g) => (
                    <option key={g} value={g}>
                      {g}
                    </option>
                  ))}
                </select>
              </Field>
            </div>
          </div>

          {/* Program */}
          <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>
                <select
                  required
                  value={form.program}
                  onChange={(e) => update("program", e.target.value)}
                  className={inputCls}
                >
                  <option value="">Select a program</option>
                  {programs.map((p) => (
                    <option key={p} value={p}>
                      {p}
                    </option>
                  ))}
                </select>
              </Field>
              <Field label="Preferred start date" required>
                <input
                  type="date"
                  required
                  value={form.startDate}
                  onChange={(e) => update("startDate", e.target.value)}
                  className={inputCls}
                />
              </Field>
            </div>
          </div>

          {/* Parent / Guardian */}
          <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>
                <input
                  type="text"
                  required
                  value={form.parentName}
                  onChange={(e) => update("parentName", e.target.value)}
                  className={inputCls}
                  placeholder="Parent or guardian name"
                />
              </Field>
              <Field label="Relationship" required>
                <select
                  required
                  value={form.relationship}
                  onChange={(e) => update("relationship", e.target.value)}
                  className={inputCls}
                >
                  <option value="">Select</option>
                  <option>Mother</option>
                  <option>Father</option>
                  <option>Guardian</option>
                  <option>Other</option>
                </select>
              </Field>
              <Field label="Email" required>
                <input
                  type="email"
                  required
                  value={form.email}
                  onChange={(e) => update("email", e.target.value)}
                  className={inputCls}
                  placeholder="you@example.com"
                />
              </Field>
              <Field label="Phone" required>
                <input
                  type="tel"
                  required
                  value={form.phone}
                  onChange={(e) => update("phone", e.target.value)}
                  className={inputCls}
                  placeholder="+254 7XX XXX XXX"
                />
              </Field>
            </div>
          </div>
        </div>
      </section>

      <section>
        <Field label="Notes (optional)">
          <textarea
            value={form.notes}
            onChange={(e) => update("notes", e.target.value)}
            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"
            checked={form.consent}
            onChange={(e) => update("consent", e.target.checked)}
            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>
      </section>

      {error && (
        <p className="mt-4 text-sm text-red-600" role="alert">
          {error}
        </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"
          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"
        >
          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,
  children,
}: {
  label: string;
  required?: boolean;
  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}
    </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>
  );
}
