import { useQuery } from "@tanstack/react-query";
import { Link } from "@tanstack/react-router";
import { useEffect, useRef, useState } from "react";
import { Field, PhoneInput, Segmented, Select, TextInput, TypedDateInput, YesNo } from "./form";
import { Card } from "./page";
import { StatusBadge } from "./status-badge";
import { Button } from "@/components/ui/button";
import { listClasses } from "@/api/delivery";
import { listRegionAliases } from "@/api/admin";
import { checkDuplicate, type TraineeInput } from "@/api/trainees";
import { fieldErrorMap } from "@/api/client";
import { useDebounce, useUnsavedChangesPrompt } from "@/lib/hooks";
import { fmtDate } from "@/lib/dates";
import { normalizePhone } from "@/lib/phone";
import { cn } from "@/lib/utils";

const NAME = /^[\p{L}\p{M}][\p{L}\p{M}' -]{0,59}$/u;
const EDU = [
  "No formal education",
  "Primary (Grades 1–8)",
  "Secondary (Grades 9–12)",
  "High school dropout",
  "TVET Certificate Level I–IV",
  "Diploma",
  "Bachelor's Degree",
  "Above Bachelor's",
  "Short-term Training",
];
const EMP = [
  "Not currently working",
  "Working occasionally",
  "Working fewer hours than desired",
  "Working full-time for an employer",
  "Self-employed / running own business",
];
const NOT_ELIGIBLE_EDU = ["No formal education", "Primary (Grades 1–8)", "Short-term Training"];
const CITY = ["Addis Ababa", "Dire Dawa"];
const INCLUSION = [
  "Person with disability",
  "IDP",
  "Returnee",
  "Low-income household",
  "None of the above",
  "Prefer not to say",
];
const EXCLUSIVE = ["None of the above", "Prefer not to say"];
const CONSENTS = [
  ["consentAccuracy", "I confirm the information provided is accurate and true.", true],
  ["consentFollowup", "I agree to be contacted for follow-up surveys.", false],
  [
    "consentVerify",
    "I agree that my employment may be verified by contacting me or my employer.",
    true,
  ],
  ["consentImage", "I agree to the use of my image.", false],
] as const;

export interface TraineeFormValues {
  classId: string;
  externalBeneficiaryId: string;
  formDate: string;
  rosterStatus: "active" | "reserve";
  firstName: string;
  fatherName: string;
  grandfatherName: string;
  sex: "" | "male" | "female";
  age: string;
  dateOfBirth: string;
  phone: string;
  phoneAlt: string;
  email: string;
  kebele: string;
  woreda: string;
  subCity: string;
  region: string;
  emergencyName: string;
  emergencyPhone: string;
  education: string;
  previouslyParticipated?: boolean | undefined;
  priorType: string;
  priorCompleted?: boolean | undefined;
  priorYear: string;
  employment: string;
  incomeSufficient?: boolean | undefined;
  skillUsage: string;
  plan: string;
  planOther: string;
  inclusion: string[];
  disability: string;
  disabilityOther: string;
  consentAccuracy?: boolean | undefined;
  consentFollowup?: boolean | undefined;
  consentVerify?: boolean | undefined;
  consentImage?: boolean | undefined;
}
export const EMPTY_TRAINEE: TraineeFormValues = {
  classId: "",
  externalBeneficiaryId: "",
  formDate: "",
  rosterStatus: "active",
  firstName: "",
  fatherName: "",
  grandfatherName: "",
  sex: "",
  age: "",
  dateOfBirth: "",
  phone: "",
  phoneAlt: "",
  email: "",
  kebele: "",
  woreda: "",
  subCity: "",
  region: "",
  emergencyName: "",
  emergencyPhone: "",
  education: "",
  priorType: "",
  priorYear: "",
  employment: "",
  skillUsage: "",
  plan: "",
  planOther: "",
  inclusion: [],
  disability: "",
  disabilityOther: "",
};

/** Same rules as the server (frontend prompt §3.4). */
export function validateTrainee(f: TraineeFormValues): Record<string, string> {
  const e: Record<string, string> = {};
  const req = (k: keyof TraineeFormValues, m = "This field is required.") => {
    const v = f[k];
    if (v === undefined || v === "" || (typeof v === "string" && !v.trim())) e[k] = m;
  };
  req("classId", "Choose a class.");
  req("formDate", "Enter the date on the form as DD/MM/YYYY.");
  (["firstName", "fatherName", "grandfatherName", "emergencyName"] as const).forEach((k) => {
    req(k);
    if (k !== "emergencyName" && f[k].trim() && !NAME.test(f[k].trim()))
      e[k] = "Use letters only, spaces, hyphen or apostrophe.";
  });
  req("sex");
  if (!/^\d{2}$/.test(f.age)) e["age"] = "Enter the age in whole years.";
  req("dateOfBirth", "Enter the date of birth as DD/MM/YYYY.");
  (["phone", "emergencyPhone"] as const).forEach((k) => {
    if (!normalizePhone(f[k]).ok) e[k] = "Enter an Ethiopian mobile number, e.g. 0911 22 33 44.";
  });
  if (f.phoneAlt.trim() && !normalizePhone(f.phoneAlt).ok)
    e["phoneAlt"] = "Enter an Ethiopian mobile number, or leave it empty.";
  if (f.email.trim() && !/^\S+@\S+\.\S+$/.test(f.email.trim()))
    e["email"] = "Enter a valid email address.";
  req("region");
  req("woreda");
  if (CITY.includes(f.region)) req("subCity", "Sub-city is required in a city administration.");
  req("education");
  req("previouslyParticipated");
  if (f.previouslyParticipated) {
    req("priorType");
    req("priorCompleted");
    if (f.priorCompleted && !/^(19|20)\d\d$/.test(f.priorYear))
      e["priorYear"] = "Enter the year as four digits.";
  }
  req("employment");
  if (f.employment && f.employment !== EMP[0]) {
    req("incomeSufficient");
    req("skillUsage");
  }
  req("plan");
  if (f.plan === "Other") req("planOther", "Specify the plan.");
  if (!f.inclusion.length) e["inclusion"] = "Choose at least one option.";
  if (f.inclusion.includes("Person with disability")) {
    req("disability", "Choose the disability type.");
    if (f.disability === "Other") req("disabilityOther", "Specify the disability.");
  }
  CONSENTS.forEach(([k, , must]) => {
    req(k, "Answer Yes or No.");
    if (must && f[k] === false) e[k] = "The trainee must agree to this to be registered.";
  });
  return e;
}
export function toInput(f: TraineeFormValues): TraineeInput {
  const s = <K extends string>(k: K, v: string) =>
    v.trim() ? ({ [k]: v.trim() } as Record<K, string>) : {};
  const works = f.employment !== EMP[0];
  return {
    classId: f.classId,
    formDate: f.formDate,
    rosterStatus: f.rosterStatus,
    firstName: f.firstName.trim(),
    fatherName: f.fatherName.trim(),
    grandfatherName: f.grandfatherName.trim(),
    sex: f.sex as "male",
    age: Number(f.age),
    dateOfBirth: f.dateOfBirth,
    phone: f.phone.trim(),
    woreda: f.woreda.trim(),
    region: f.region,
    emergencyName: f.emergencyName.trim(),
    emergencyPhone: f.emergencyPhone.trim(),
    education: f.education,
    previouslyParticipated: !!f.previouslyParticipated,
    employment: f.employment,
    plan: f.plan,
    inclusion: f.inclusion,
    consentAccuracy: !!f.consentAccuracy,
    consentFollowup: !!f.consentFollowup,
    consentVerify: !!f.consentVerify,
    consentImage: !!f.consentImage,
    ...s("externalBeneficiaryId", f.externalBeneficiaryId),
    ...s("phoneAlt", f.phoneAlt),
    ...s("email", f.email.toLowerCase()),
    ...s("kebele", f.kebele),
    ...s("subCity", f.subCity),
    ...(f.previouslyParticipated
      ? {
          ...s("priorType", f.priorType),
          priorCompleted: !!f.priorCompleted,
          ...(f.priorCompleted ? { priorYear: Number(f.priorYear) } : {}),
        }
      : {}),
    ...(works ? { incomeSufficient: !!f.incomeSufficient, ...s("skillUsage", f.skillUsage) } : {}),
    ...(f.plan === "Other" ? s("planOther", f.planOther) : {}),
    ...(f.inclusion.includes("Person with disability")
      ? {
          ...s("disability", f.disability),
          ...(f.disability === "Other" ? s("disabilityOther", f.disabilityOther) : {}),
        }
      : {}),
  };
}

/** Editing an existing trainee: the class and roster stay as they are (moved elsewhere). */
export interface TraineeEdit {
  id: string;
  initial: TraineeFormValues;
  classLabel: string;
  onSave: (changes: Partial<TraineeInput>) => void;
}
/** Official registration form (prompt §5.6.3), one page with a section index. */
export function TraineeForm({
  pid,
  error,
  pending,
  onSubmit,
  edit,
}: {
  pid: string;
  error: Error | null;
  pending: boolean;
  onSubmit?: (i: TraineeInput) => void;
  edit?: TraineeEdit;
}) {
  const base = edit?.initial ?? EMPTY_TRAINEE;
  const [f, setF] = useState<TraineeFormValues>(base);
  const [err, setErr] = useState<Record<string, string>>({});
  const [dupOk, setDupOk] = useState("");
  const sum = useRef<HTMLDivElement>(null);
  const set = <K extends keyof TraineeFormValues>(k: K, v: TraineeFormValues[K]) => {
    setF((s) => ({ ...s, [k]: v }));
    setErr((e) => {
      const n = { ...e };
      delete n[k];
      return n;
    });
  };
  const cls = useQuery({
    queryKey: ["classes", "all"],
    queryFn: () => listClasses({ pageSize: 500 }),
  });
  const regions = useQuery({
    queryKey: ["regions"],
    queryFn: listRegionAliases,
    staleTime: Infinity,
  });
  useEffect(() => {
    const m = fieldErrorMap(error);
    if (error) {
      setErr(m);
      sum.current?.focus();
    }
  }, [error]);
  useUnsavedChangesPrompt(!pending && JSON.stringify(f) !== JSON.stringify(base));
  const key = useDebounce(
    {
      firstName: f.firstName.trim(),
      fatherName: f.fatherName.trim(),
      grandfatherName: f.grandfatherName.trim(),
      phone: f.phone,
      ...(f.dateOfBirth ? { dateOfBirth: f.dateOfBirth } : {}),
      ...(f.sex ? { sex: f.sex } : {}),
    },
    500,
  );
  const dup = useQuery({
    queryKey: ["dup-check", key],
    queryFn: async () => (await checkDuplicate(key)) ?? null,
    enabled:
      !!key.firstName && !!key.fatherName && !!key.grandfatherName && normalizePhone(key.phone).ok,
  });
  const hit =
    dup.data && dupOk !== dup.data.trainee.id && dup.data.trainee.id !== edit?.id
      ? dup.data
      : undefined;
  const age = Number(f.age);
  const reasons = [
    ...(f.age && (age < 18 || age > 29) ? [`age ${f.age} is outside 18–29`] : []),
    ...(NOT_ELIGIBLE_EDU.includes(f.education) ? ["education level"] : []),
    ...(EMP.indexOf(f.employment) > 2 ? ["already working"] : []),
  ];
  const submit = () => {
    const all = validateTrainee(f);
    // Editing: only fields that were changed must pass, so a gap in an old record never blocks a fix.
    const e = edit
      ? Object.fromEntries(
          Object.entries(all).filter(
            ([k]) =>
              k !== "classId" &&
              JSON.stringify(f[k as keyof TraineeFormValues]) !==
                JSON.stringify(base[k as keyof TraineeFormValues]),
          ),
        )
      : all;
    setErr(e);
    if (Object.keys(e).length) {
      setTimeout(() => sum.current?.focus(), 0);
      return;
    }
    if (hit) return;
    if (!edit) return onSubmit?.(toInput(f));
    const now = toInput(f) as unknown as Record<string, unknown>,
      was = toInput(base) as unknown as Record<string, unknown>;
    edit.onSave(
      Object.fromEntries(
        Object.entries(now).filter(
          ([k, v]) =>
            k !== "classId" && k !== "rosterStatus" && JSON.stringify(v) !== JSON.stringify(was[k]),
        ),
      ) as Partial<TraineeInput>,
    );
  };
  const txt = (k: keyof TraineeFormValues, label: string, required = false, help?: string) => (
    <Field label={label} required={required} error={err[k]} help={help}>
      <TextInput value={f[k] as string} onChange={(v) => set(k, v as never)} error={err[k]} />
    </Field>
  );
  const sel = (
    k: keyof TraineeFormValues,
    label: string,
    options: (string | [string, string])[],
    required = true,
  ) => (
    <Field label={label} required={required} error={err[k]}>
      <Select
        value={f[k] as string}
        onChange={(v) => set(k, v as never)}
        // An old record may hold a value that is no longer offered: keep it visible.
        options={
          f[k] && !options.some((o) => (Array.isArray(o) ? o[0] : o) === f[k])
            ? [f[k] as string, ...options]
            : options
        }
        error={err[k]}
      />
    </Field>
  );
  const yn = (k: keyof TraineeFormValues, label: string) => (
    <Field label={label} required error={err[k]}>
      <YesNo
        name={k}
        value={f[k] as boolean | undefined}
        onChange={(v) => set(k, v as never)}
        error={err[k]}
      />
    </Field>
  );
  const open = (cls.data?.items ?? []).filter((c) => c.registrationOpen);
  const chosen = open.find((c) => c.id === f.classId);
  const errCount = Object.keys(err).length;
  const grid = "grid gap-4 sm:grid-cols-2 lg:grid-cols-3";
  const sec = [
    ["programme", "Programme"],
    ["personal", "Personal & contact"],
    ["education", "Education"],
    ["employment", "Employment"],
    ["inclusion", "Inclusion"],
    ["consent", "Consent"],
  ] as const;
  return (
    <div className="grid gap-6 lg:grid-cols-[180px_minmax(0,1fr)]">
      <nav aria-label="Form sections" className="hidden lg:block">
        <ul className="sticky top-20 space-y-1 text-[13px]">
          {sec.map(([id, l]) => (
            <li key={id}>
              <a
                href={`#${id}`}
                className="block rounded px-2 py-1.5 text-muted-foreground hover:bg-surface-2 hover:text-foreground"
              >
                {l}
              </a>
            </li>
          ))}
        </ul>
      </nav>
      <form
        noValidate
        className="max-w-4xl space-y-5"
        onSubmit={(e) => {
          e.preventDefault();
          submit();
        }}
      >
        {(errCount > 0 || error) && (
          <div
            ref={sum}
            tabIndex={-1}
            role="alert"
            className="rounded-lg border border-danger/30 bg-danger-soft p-3 text-[13px] text-danger"
          >
            <b>
              {error?.message && !errCount
                ? error.message
                : `Fix ${errCount} field${errCount === 1 ? "" : "s"} to save this trainee.`}
            </b>
            {errCount > 0 && (
              <ul className="mt-1 list-disc pl-5">
                {Object.values(err)
                  .slice(0, 6)
                  .map((m, i) => (
                    <li key={i}>{m}</li>
                  ))}
                {errCount > 6 && <li>and {errCount - 6} more, marked below</li>}
              </ul>
            )}
          </div>
        )}
        {!edit && cls.isSuccess && open.length === 0 && (
          <p role="status" className="rounded-lg bg-info-soft p-3 text-[13px]">
            Registration is closed for every class. M&amp;E can reopen it for a provider.
          </p>
        )}
        <section id="programme">
          <Card title="Programme">
            <div className={grid}>
              {edit ? (
                <Field label="Class">
                  <p className="py-2 text-[13px]">{edit.classLabel}</p>
                </Field>
              ) : (
                <Field
                  label="Class"
                  required
                  error={err["classId"]}
                  help={
                    chosen
                      ? `${fmtDate(chosen.effectiveStart)} to ${fmtDate(chosen.effectiveEnd)}. Registration closes on ${fmtDate(chosen.registrationClosesOn)}.`
                      : undefined
                  }
                >
                  <Select
                    value={f.classId}
                    onChange={(v) => set("classId", v)}
                    options={open.map((c) => [
                      c.id,
                      `${c.code} · ${c.trainingTitle} · ${c.locationName}`,
                    ])}
                    error={err["classId"]}
                  />
                </Field>
              )}
              <Field label="Date on the form" required error={err["formDate"]}>
                <TypedDateInput
                  value={f.formDate}
                  onChange={(v) => set("formDate", v)}
                  error={err["formDate"]}
                />
              </Field>
              {!edit && (
                <Field label="Roster status" required>
                  <Segmented
                    value={f.rosterStatus}
                    onChange={(v) => set("rosterStatus", v)}
                    options={[
                      ["active", "Active"],
                      ["reserve", "Reserve"],
                    ]}
                  />
                </Field>
              )}
              {txt(
                "externalBeneficiaryId",
                "External beneficiary ID",
                false,
                "Only if the provider uses one.",
              )}
            </div>
          </Card>
        </section>
        <section id="personal">
          <Card title="Personal & contact">
            <div className={grid}>
              {txt("firstName", "First name", true)}
              {txt("fatherName", "Father's name", true)}
              {txt("grandfatherName", "Grandfather's name", true)}
              <Field label="Sex" required error={err["sex"]}>
                <Segmented
                  value={f.sex || undefined}
                  onChange={(v) => set("sex", v)}
                  options={[
                    ["male", "Male"],
                    ["female", "Female"],
                  ]}
                />
              </Field>
              <Field label="Age (years)" required error={err["age"]}>
                <TextInput
                  inputMode="numeric"
                  maxLength={2}
                  value={f.age}
                  onChange={(v) => set("age", v.replace(/\D/g, ""))}
                  error={err["age"]}
                />
              </Field>
              <Field
                label="Date of birth"
                required
                error={err["dateOfBirth"]}
                className="sm:col-span-2 lg:col-span-3 lg:max-w-md"
              >
                <TypedDateInput
                  value={f.dateOfBirth}
                  onChange={(v) => set("dateOfBirth", v)}
                  error={err["dateOfBirth"]}
                />
              </Field>
              <Field label="Phone" required error={err["phone"]}>
                <PhoneInput
                  value={f.phone}
                  onChange={(v) => set("phone", v)}
                  error={err["phone"]}
                />
              </Field>
              <Field label="Alternative phone" error={err["phoneAlt"]}>
                <PhoneInput
                  value={f.phoneAlt}
                  onChange={(v) => set("phoneAlt", v)}
                  error={err["phoneAlt"]}
                />
              </Field>
              {txt("email", "Email")}
              {sel(
                "region",
                "Region",
                (regions.data?.regions ?? []).map((r) => r.name),
              )}
              {CITY.includes(f.region) && txt("subCity", "Sub-city", true)}
              {txt("woreda", "Woreda", true)}
              {txt("kebele", "Kebele")}
              {txt("emergencyName", "Emergency contact name", true)}
              <Field label="Emergency contact phone" required error={err["emergencyPhone"]}>
                <PhoneInput
                  value={f.emergencyPhone}
                  onChange={(v) => set("emergencyPhone", v)}
                  error={err["emergencyPhone"]}
                />
              </Field>
            </div>
            {hit && (
              <div
                role="status"
                className="mt-4 rounded-lg border border-amber bg-amber-soft p-3 text-[13px]"
              >
                <p>
                  <b>Possible duplicate:</b> {hit.trainee.fullName}, {hit.trainee.code} (
                  {hit.trainee.providerCode}, {hit.trainee.className}). {hit.score} % match:{" "}
                  {hit.reasons.join(", ")}.
                </p>
                <div className="mt-2 flex gap-2">
                  <Button asChild size="sm" variant="outline">
                    <Link
                      to="/p/$pid/trainees/$id"
                      params={{ pid, id: hit.trainee.id }}
                      target="_blank"
                    >
                      View record
                    </Link>
                  </Button>
                  <Button
                    type="button"
                    size="sm"
                    variant="outline"
                    onClick={() => setDupOk(hit.trainee.id)}
                  >
                    This is a different person
                  </Button>
                </div>
              </div>
            )}
          </Card>
        </section>
        <section id="education">
          <Card title="Education & background">
            <div className={grid}>
              {sel("education", "Highest education", EDU)}
              {yn("previouslyParticipated", "Took skills training before?")}
              {f.previouslyParticipated && (
                <>
                  {txt("priorType", "Type or field of that training", true)}
                  {yn("priorCompleted", "Completed it?")}
                  {f.priorCompleted && txt("priorYear", "Year completed", true)}
                </>
              )}
            </div>
          </Card>
        </section>
        <section id="employment">
          <Card title="Employment (last month)">
            <div className={grid}>
              {sel("employment", "Status", EMP)}
              {f.employment && f.employment !== EMP[0] && (
                <>
                  {yn("incomeSufficient", "Is the income sufficient?")}
                  {sel("skillUsage", "Use of skills at work", ["Fully", "Partially", "Not at all"])}
                </>
              )}
              {sel("plan", "Plan after training", ["Wage employment", "Self-employment", "Other"])}
              {f.plan === "Other" && txt("planOther", "Specify the plan", true)}
            </div>
            {f.age && f.education && f.employment && (
              <p className="mt-4">
                {reasons.length ? (
                  <StatusBadge
                    status="not_eligible"
                    label={`Not eligible: ${reasons.join(", ")}`}
                  />
                ) : (
                  <StatusBadge status="eligible" />
                )}
              </p>
            )}
          </Card>
        </section>
        <section id="inclusion">
          <Card title="Inclusion">
            <Field label="Select all that apply" required error={err["inclusion"]}>
              <div className="flex flex-wrap gap-2">
                {INCLUSION.map((o) => {
                  const on = f.inclusion.includes(o);
                  return (
                    <button
                      key={o}
                      type="button"
                      aria-pressed={on}
                      onClick={() =>
                        set(
                          "inclusion",
                          on
                            ? f.inclusion.filter((x) => x !== o)
                            : EXCLUSIVE.includes(o)
                              ? [o]
                              : [...f.inclusion.filter((x) => !EXCLUSIVE.includes(x)), o],
                        )
                      }
                      className={cn(
                        "min-h-9 rounded-md border px-3 py-1.5 text-[13px]",
                        on
                          ? "border-primary bg-primary text-primary-foreground"
                          : "bg-card hover:bg-surface-2",
                      )}
                    >
                      {o}
                    </button>
                  );
                })}
              </div>
            </Field>
            {f.inclusion.includes("Person with disability") && (
              <div className={cn(grid, "mt-4")}>
                {sel("disability", "Disability type", [
                  "Hearing",
                  "Visual",
                  "Paralysis",
                  "Prefer not to say",
                  "Other",
                ])}
                {f.disability === "Other" && txt("disabilityOther", "Specify", true)}
              </div>
            )}
          </Card>
        </section>
        <section id="consent">
          <Card title="Consent">
            <div className="space-y-4">
              {CONSENTS.map(([k, l]) => (
                <div key={k}>{yn(k, l)}</div>
              ))}
            </div>
          </Card>
        </section>
        <div className="sticky bottom-0 z-10 flex justify-end gap-2 border-t bg-background py-3">
          <Button type="button" variant="outline" asChild>
            {edit ? (
              <Link to="/p/$pid/trainees/$id" params={{ pid, id: edit.id }}>
                Cancel
              </Link>
            ) : (
              <Link to="/p/$pid/trainees" params={{ pid }}>
                Cancel
              </Link>
            )}
          </Button>
          <Button type="submit" disabled={pending || !!hit}>
            {pending ? "Saving…" : edit ? "Save changes" : "Save trainee"}
          </Button>
        </div>
      </form>
    </div>
  );
}
