import { createFileRoute, Link, useNavigate } from "@tanstack/react-router";
import { useQuery } from "@tanstack/react-query";
import { useState } from "react";
import { Card, PageHeader } from "@/components/pbps/page";
import { Field, FormError, PhoneInput, Select, TextInput } from "@/components/pbps/form";
import { useAct, View } from "@/components/pbps/blocks";
import { DetailSkeleton } from "@/components/pbps/states";
import { Button } from "@/components/ui/button";
import { getClass } from "@/api/delivery";
import { listRegionAliases } from "@/api/admin";
import { fieldErrorMap } from "@/api/client";
import { getTrainee, updateTrainee, type TraineeInput } from "@/api/trainees";
import { TraineeForm, type TraineeFormValues } from "@/components/pbps/trainee-form";
import type { Trainee } from "@/api/types";
import { useCan } from "@/lib/access";
import { normalizePhone } from "@/lib/phone";
import { P } from "@/lib/roles";

export const Route = createFileRoute("/p/$pid/trainees/$id/edit")({ component: Page });
function Page() {
  const { id } = Route.useParams();
  const q = useQuery({ queryKey: ["trainees", id], queryFn: () => getTrainee(id) });
  return (
    <View q={q} skeleton={<DetailSkeleton />}>
      {(t) => <Choose key={t.id} t={t} />}
    </View>
  );
}
/** While registration is open every answer can be corrected; after that only how to reach the trainee. */
function Choose({ t }: { t: Trainee }) {
  const cls = useQuery({ queryKey: ["classes", t.classId], queryFn: () => getClass(t.classId) });
  if (cls.isPending) return <DetailSkeleton />;
  return cls.data?.cls.registrationOpen ? <Full t={t} /> : <Edit t={t} />;
}
const LABEL: Record<string, string> = {
  "Internally displaced person": "IDP",
  "Low income": "Low-income household",
};
const s = (v: string | number | undefined | null) =>
  v === undefined || v === null ? "" : String(v);
const toForm = (t: Trainee): TraineeFormValues => ({
  classId: t.classId,
  externalBeneficiaryId: s(t.externalBeneficiaryId),
  formDate: s(t.formDate).slice(0, 10),
  rosterStatus: t.rosterStatus === "reserve" ? "reserve" : "active",
  firstName: t.firstName,
  fatherName: t.fatherName,
  grandfatherName: t.grandfatherName,
  sex: t.sex,
  age: s(t.age),
  dateOfBirth: s(t.dateOfBirth).slice(0, 10),
  phone: t.phone,
  phoneAlt: s(t.phoneAlt),
  email: s(t.email),
  kebele: s(t.kebele),
  woreda: t.woreda,
  subCity: s(t.subCity),
  region: t.region,
  emergencyName: s(t.emergencyName),
  emergencyPhone: s(t.emergencyPhone),
  education: t.education,
  previouslyParticipated: t.previouslyParticipated,
  priorType: s(t.priorType),
  priorCompleted: t.priorCompleted,
  priorYear: s(t.priorYear),
  employment: t.employment,
  incomeSufficient: t.incomeSufficient,
  skillUsage: s(t.skillUsage),
  plan: s(t.plan),
  planOther: s(t.planOther),
  inclusion: (t.inclusion ?? []).map((x) => LABEL[x] ?? x),
  disability: s(t.disability),
  disabilityOther: s(t.disabilityOther),
  consentAccuracy: t.consentAccuracy,
  consentFollowup: t.consentFollowup,
  consentVerify: t.consentVerify,
  consentImage: t.consentImage,
});
function Full({ t }: { t: Trainee }) {
  const { pid, id } = Route.useParams();
  const navigate = useNavigate();
  const back = () =>
    void navigate({ to: "/p/$pid/trainees/$id", params: { pid, id }, ignoreBlocker: true });
  const m = useAct((b: Partial<TraineeInput>) => updateTrainee(id, b), {
    success: "Trainee updated",
    refresh: ["trainees", "classes", "providers"],
    onError: () => {},
    onDone: back,
  });
  return (
    <>
      <PageHeader title={`Edit ${t.fullName}`} description={t.code} />
      <TraineeForm
        pid={pid}
        error={m.error}
        pending={m.isPending}
        edit={{
          id,
          initial: toForm(t),
          classLabel: `${t.className} · ${t.trainingTitle} · ${t.siteName}`,
          onSave: (b) => (Object.keys(b).length ? m.mutate(b) : back()),
        }}
      />
    </>
  );
}
const NAME = /^[\p{L}\p{M}][\p{L}\p{M}' -]{0,59}$/u;
function Edit({ t }: { t: Trainee }) {
  const { pid, id } = Route.useParams();
  const navigate = useNavigate();
  const cls = useQuery({ queryKey: ["classes", t.classId], queryFn: () => getClass(t.classId) });
  const regions = useQuery({
    queryKey: ["regions"],
    queryFn: listRegionAliases,
    staleTime: Infinity,
  });
  const start = {
    firstName: t.firstName,
    fatherName: t.fatherName,
    grandfatherName: t.grandfatherName,
    phone: t.phone,
    region: t.region,
    woreda: t.woreda,
  };
  const [f, setF] = useState(start);
  const [err, setErr] = useState<Record<string, string>>({});
  const admin = useCan(P.projectManage);
  const frozen = cls.isSuccess && !cls.data.cls.registrationOpen;
  const m = useAct((b: Partial<typeof start>) => updateTrainee(id, b), {
    success: "Trainee updated",
    refresh: ["trainees"],
    onError: (e) => setErr(fieldErrorMap(e)),
    onDone: () => void navigate({ to: "/p/$pid/trainees/$id", params: { pid, id } }),
  });
  const save = () => {
    const e: Record<string, string> = {};
    (["firstName", "fatherName", "grandfatherName"] as const).forEach((k) => {
      if (!NAME.test(f[k].trim())) e[k] = "Use letters only, spaces, hyphen or apostrophe.";
    });
    if (!normalizePhone(f.phone).ok)
      e["phone"] = "Enter an Ethiopian mobile number, e.g. 0911 22 33 44.";
    if (!f.region) e["region"] = "Choose a region.";
    if (!f.woreda.trim()) e["woreda"] = "Woreda is required.";
    setErr(e);
    if (Object.keys(e).length) return;
    // Send only what changed, so a locked field never blocks a contact update.
    m.mutate(
      Object.fromEntries(
        (Object.keys(f) as (keyof typeof f)[])
          .filter((k) => f[k] !== start[k])
          .map((k) => [k, f[k].trim()]),
      ),
    );
  };
  const txt = (k: keyof typeof f, label: string, locked = false) => (
    <Field label={label} required error={err[k]}>
      <TextInput
        value={f[k]}
        disabled={locked}
        onChange={(v) => setF((s) => ({ ...s, [k]: v }))}
        error={err[k]}
      />
    </Field>
  );
  return (
    <>
      <PageHeader title={`Edit ${t.fullName}`} description={t.code} />
      <form
        noValidate
        className="max-w-3xl space-y-5"
        onSubmit={(e) => {
          e.preventDefault();
          save();
        }}
      >
        <FormError error={m.error} />
        <Card title="Identity">
          {frozen && (
            <p className="mb-4 rounded-lg bg-info-soft p-3 text-[13px]">
              {cls.data?.cls.registrationClosedReason} Nothing can be changed
              {admin ? ", except how to contact the trainee." : ". M&E can reopen it."}
            </p>
          )}
          <div className="grid gap-4 sm:grid-cols-3">
            {txt("firstName", "First name", frozen)}
            {txt("fatherName", "Father's name", frozen)}
            {txt("grandfatherName", "Grandfather's name", frozen)}
          </div>
        </Card>
        <Card title="Contact">
          <div className="grid gap-4 sm:grid-cols-3">
            <Field label="Phone" required error={err["phone"]}>
              <PhoneInput
                value={f.phone}
                onChange={(v) => setF((s) => ({ ...s, phone: v }))}
                error={err["phone"]}
              />
            </Field>
            <Field label="Region" required error={err["region"]}>
              <Select
                value={f.region}
                onChange={(v) => setF((s) => ({ ...s, region: v }))}
                options={(regions.data?.regions ?? [{ code: "", name: f.region }]).map(
                  (r) => r.name,
                )}
              />
            </Field>
            {txt("woreda", "Woreda", frozen)}
          </div>
        </Card>
        <div className="flex justify-end gap-2">
          <Button type="button" variant="outline" asChild>
            <Link to="/p/$pid/trainees/$id" params={{ pid, id }}>
              Cancel
            </Link>
          </Button>
          <Button type="submit" disabled={m.isPending || cls.isPending || (frozen && !admin)}>
            {m.isPending ? "Saving…" : "Save changes"}
          </Button>
        </div>
      </form>
    </>
  );
}
