import { createFileRoute, Link, useNavigate } from "@tanstack/react-router";
import { useQuery } from "@tanstack/react-query";
import { useState } from "react";
import { Check } from "lucide-react";
import { Card, DateText, PageHeader } from "@/components/pbps/page";
import { Field, FormError, PhoneInput, TextInput, YesNo } from "@/components/pbps/form";
import { Dl, Tbl, useAct, View } from "@/components/pbps/blocks";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { listLocations } from "@/api/admin";
import {
  activateProvider,
  createProvider,
  listTargets,
  previewObligations,
  type OnboardingInput,
} from "@/api/programme";
import { fmtDate } from "@/lib/dates";
import { useUnsavedChangesPrompt } from "@/lib/hooks";
import { normalizePhone } from "@/lib/phone";
import { cn } from "@/lib/utils";

export const Route = createFileRoute("/p/$pid/providers/new")({ component: Page });
const EMAIL = /^\S+@\S+\.\S+$/;
const STEPS = [
  "Profile",
  "Contract",
  "Targets",
  "Organisation admin",
  "Registration window",
  "Review",
];
const EMPTY = {
  code: "",
  name: "",
  legalName: "",
  contactName: "",
  contactPhone: "",
  notificationEmail: "",
  replyToEmail: "",
  requiresExternalId: false,
  externalIdLabel: "",
  number: "",
  signedDate: "",
  start: "",
  end: "",
  target: "",
  levels: [] as string[],
  locationCodes: [] as string[],
  adminName: "",
  adminEmail: "",
  from: "",
  until: "",
};
type F = typeof EMPTY;
function problems(f: F, step: number): Record<string, string> {
  const e: Record<string, string> = {};
  const req = (...ks: (keyof F)[]) =>
    ks.forEach((k) => {
      if (!String(f[k]).trim()) e[k] = "This field is required.";
    });
  if (step === 0) {
    req("name", "contactName");
    if (!/^[A-Z]{2,10}$/.test(f.code)) e["code"] = "Use 2–10 capital letters.";
    if (!normalizePhone(f.contactPhone).ok) e["contactPhone"] = "Enter an Ethiopian mobile number.";
    (["notificationEmail", "replyToEmail"] as const).forEach((k) => {
      if (!EMAIL.test(f[k].trim())) e[k] = "Enter a valid email address.";
    });
    if (f.requiresExternalId) req("externalIdLabel");
  }
  if (step === 1) {
    req("number", "signedDate", "start", "end");
    if (f.start && f.end && f.end <= f.start) e["end"] = "End must be after start.";
    if (!/^[1-9]\d{0,5}$/.test(f.target)) e["target"] = "Enter a whole number above 0.";
    if (!f.levels.length) e["levels"] = "Choose at least one level.";
    if (!f.locationCodes.length) e["locationCodes"] = "Choose at least one site.";
  }
  if (step === 3) {
    req("adminName");
    if (!EMAIL.test(f.adminEmail.trim())) e["adminEmail"] = "Enter a valid email address.";
  }
  if (step === 4) {
    req("from", "until");
    if (f.from && f.until && f.until < f.from) e["until"] = "Must be after the opening date.";
  }
  return e;
}
function Page() {
  const { pid } = Route.useParams();
  const navigate = useNavigate();
  const [f, setF] = useState(EMPTY);
  const [step, setStep] = useState(0);
  const [err, setErr] = useState<Record<string, string>>({});
  const [tg, setTg] = useState<Record<string, string>>({});
  const [created, setCreated] = useState<string>();
  const set = <K extends keyof F>(k: K, v: F[K]) => setF((s) => ({ ...s, [k]: v }));
  const locs = useQuery({ queryKey: ["locations"], queryFn: listLocations });
  const targets = useQuery({ queryKey: ["targets"], queryFn: listTargets });
  useUnsavedChangesPrompt(!created && f !== EMPTY);
  const tgErr = Object.fromEntries(
    (targets.data?.indicators ?? [])
      .filter((i) => {
        const v = tg[i.code];
        return (
          v !== undefined &&
          v !== "" &&
          (!Number.isFinite(Number(v)) || Number(v) < 0 || (i.unit === "%" && Number(v) > 100))
        );
      })
      .map((i) => [i.code, true]),
  );
  const create = useAct((i: OnboardingInput) => createProvider(i), {
    success: "Provider created",
    refresh: ["providers", "targets"],
    onError: () => {},
    onDone: (p) => setCreated(p.id),
  });
  const go = (to: number) => {
    if (to > step)
      for (let s = step; s < to; s++) {
        const e = problems(f, s);
        if (Object.keys(e).length || (s === 2 && Object.keys(tgErr).length)) {
          setErr(e);
          setStep(s);
          return;
        }
      }
    setErr({});
    setStep(to);
  };
  const save = () =>
    create.mutate({
      code: f.code,
      name: f.name.trim(),
      ...(f.legalName ? { legalName: f.legalName } : {}),
      contactName: f.contactName,
      contactPhone: f.contactPhone,
      notificationEmail: f.notificationEmail,
      replyToEmail: f.replyToEmail,
      requiresExternalId: f.requiresExternalId,
      ...(f.externalIdLabel ? { externalIdLabel: f.externalIdLabel } : {}),
      contract: {
        number: f.number,
        signedDate: f.signedDate,
        start: f.start,
        end: f.end,
        target: Number(f.target),
        levels: f.levels,
        locationCodes: f.locationCodes,
      },
      targets: Object.fromEntries(
        Object.entries(tg)
          .filter(([, v]) => v !== "")
          .map(([k, v]) => [k, Number(v)]),
      ),
      admin: { name: f.adminName, email: f.adminEmail.toLowerCase() },
      registrationWindow: { from: f.from, until: f.until },
    });
  const txt = (
    k:
      | "code"
      | "name"
      | "legalName"
      | "contactName"
      | "notificationEmail"
      | "replyToEmail"
      | "externalIdLabel"
      | "number"
      | "target"
      | "adminName"
      | "adminEmail",
    l: string,
    req = true,
    help?: string,
  ) => (
    <Field label={l} required={req} error={err[k]} help={help}>
      <TextInput
        value={f[k]}
        onChange={(v) => set(k, k === "code" ? v.toUpperCase() : v)}
        error={err[k]}
      />
    </Field>
  );
  const date = (k: "signedDate" | "start" | "end" | "from" | "until", l: string) => (
    <Field label={l} required error={err[k]}>
      <Input type="date" value={f[k]} onChange={(e) => set(k, e.target.value)} />
    </Field>
  );
  const multi = (k: "levels" | "locationCodes", l: string, o: [string, string][]) => (
    <Field label={l} required error={err[k]} className="sm:col-span-2">
      <div className="flex flex-wrap gap-2">
        {o.map(([v, t]) => {
          const on = f[k].includes(v);
          return (
            <button
              key={v}
              type="button"
              aria-pressed={on}
              onClick={() => set(k, on ? f[k].filter((x) => x !== v) : [...f[k], v])}
              className={cn(
                "min-h-9 rounded-md border px-3 text-[13px]",
                on
                  ? "border-primary bg-primary text-primary-foreground"
                  : "bg-card hover:bg-surface-2",
              )}
            >
              {t}
            </button>
          );
        })}
      </div>
    </Field>
  );
  if (created)
    return (
      <>
        <PageHeader
          title={`Activate ${f.name}`}
          description="Activation creates these obligations. The provider stays in onboarding until then."
        />
        <Activate
          id={created}
          onDone={() =>
            void navigate({ to: "/p/$pid/providers/$id", params: { pid, id: created } })
          }
        />
      </>
    );
  const grid = "grid gap-4 sm:grid-cols-2";
  return (
    <>
      <PageHeader
        title="New training provider"
        actions={
          <Button variant="outline" asChild>
            <Link to="/p/$pid/providers" params={{ pid }}>
              Cancel
            </Link>
          </Button>
        }
      />
      <div className="grid gap-6 md:grid-cols-[200px_minmax(0,1fr)]">
        <ol className="flex gap-1 overflow-x-auto md:block md:space-y-1">
          {STEPS.map((s, i) => (
            <li key={s}>
              <button
                type="button"
                aria-current={i === step ? "step" : undefined}
                onClick={() => go(i)}
                className={cn(
                  "flex min-h-9 w-full items-center gap-2 whitespace-nowrap rounded-md px-3 text-left text-[13px]",
                  i === step
                    ? "bg-primary-soft font-medium text-primary"
                    : "text-muted-foreground hover:bg-surface-2",
                )}
              >
                {i < step && <Check className="h-4 w-4" />}
                {s}
              </button>
            </li>
          ))}
        </ol>
        <Card title={STEPS[step]}>
          <FormError error={create.error} />
          <form
            noValidate
            onSubmit={(e) => {
              e.preventDefault();
              if (step < 5) go(step + 1);
              else save();
            }}
          >
            {step === 0 && (
              <div className={grid}>
                {txt(
                  "code",
                  "Code",
                  true,
                  "2–10 capital letters. It becomes part of every trainee ID.",
                )}
                {txt("name", "Name")}
                {txt("legalName", "Legal name", false)}
                {txt("contactName", "Contact person")}
                <Field label="Contact phone" required error={err["contactPhone"]}>
                  <PhoneInput
                    value={f.contactPhone}
                    onChange={(v) => set("contactPhone", v)}
                    error={err["contactPhone"]}
                  />
                </Field>
                {txt("notificationEmail", "Notification email", true, "System emails go here.")}
                {txt(
                  "replyToEmail",
                  "Reply-to email",
                  true,
                  "Shown to people who submit feedback.",
                )}
                <Field label="Uses its own beneficiary ID?" required>
                  <YesNo
                    name="ext"
                    value={f.requiresExternalId}
                    onChange={(v) => set("requiresExternalId", v)}
                  />
                </Field>
                {f.requiresExternalId && txt("externalIdLabel", "Name of that ID")}
              </div>
            )}
            {step === 1 && (
              <div className={grid}>
                {txt("number", "Contract number")}
                {date("signedDate", "Signed on")}
                {date("start", "Start")}
                {date("end", "End")}
                {txt(
                  "target",
                  "Target trainees",
                  true,
                  /^[1-9]\d*$/.test(f.target)
                    ? `Up to ${Math.floor(Number(f.target) * 1.15)} may be registered (target + 15 %).`
                    : undefined,
                )}
                {multi("levels", "Levels", [
                  ["basic", "Basic"],
                  ["intermediate", "Intermediate"],
                  ["advanced", "Advanced"],
                ])}
                {multi(
                  "locationCodes",
                  "Sites",
                  (locs.data ?? []).filter((l) => l.active).map((l) => [l.code, l.name]),
                )}
              </div>
            )}
            {step === 2 && (
              <>
                <p className="mb-3 text-[13px] text-muted-foreground">
                  Leave a target empty to use the project default.
                </p>
                <View q={targets}>
                  {(d) => (
                    <Tbl head={["#", "Indicator", ">Default", "Provider target"]}>
                      {d.indicators.map((i) => (
                        <tr key={i.code}>
                          <td>{i.no}</td>
                          <td>{i.name}</td>
                          <td className="whitespace-nowrap text-right">
                            {i.direction === "lower_is_better" ? "≤" : "≥"} {i.defaultTarget}
                            {i.unit === "%" && " %"}
                          </td>
                          <td>
                            <TextInput
                              className="w-24"
                              inputMode="decimal"
                              aria-label={`Target for ${i.name}`}
                              error={tgErr[i.code] ? "Invalid" : undefined}
                              value={tg[i.code] ?? ""}
                              onChange={(v) => setTg((s) => ({ ...s, [i.code]: v }))}
                            />
                          </td>
                        </tr>
                      ))}
                    </Tbl>
                  )}
                </View>
                {Object.keys(tgErr).length > 0 && (
                  <p role="alert" className="mt-2 text-[13px] text-danger">
                    Use numbers of 0 or more; percentages up to 100.
                  </p>
                )}
              </>
            )}
            {step === 3 && (
              <div className={grid}>
                {txt("adminName", "Full name")}
                {txt("adminEmail", "Email", true, "Receives an invitation link to set a password.")}
              </div>
            )}
            {step === 4 && (
              <div className={grid}>
                {date("from", "Open from")}
                {date("until", "Open until")}
              </div>
            )}
            {step === 5 && (
              <Dl
                cols={2}
                items={[
                  ["Provider", `${f.name} (${f.code})`],
                  ["Contact", `${f.contactName}, ${f.contactPhone}`],
                  ["Emails", `${f.notificationEmail}, ${f.replyToEmail}`],
                  ["Contract", `${f.number}: ${f.target} trainees, ${f.start} to ${f.end}`],
                  ["Levels and sites", `${f.levels.join(", ")}; ${f.locationCodes.join(", ")}`],
                  [
                    "Own targets",
                    `${Object.values(tg).filter(Boolean).length} of ${targets.data?.indicators.length ?? 19}`,
                  ],
                  ["Admin", `${f.adminName}, ${f.adminEmail}`],
                  ["Registration", `${fmtDate(f.from)} to ${fmtDate(f.until)}`],
                ]}
              />
            )}
            <div className="mt-6 flex justify-between">
              <Button
                type="button"
                variant="outline"
                disabled={step === 0}
                onClick={() => go(step - 1)}
              >
                Back
              </Button>
              <Button type="submit" disabled={create.isPending}>
                {step < 5 ? "Continue" : create.isPending ? "Creating…" : "Create provider"}
              </Button>
            </div>
          </form>
        </Card>
      </div>
    </>
  );
}
function Activate({ id, onDone }: { id: string; onDone: () => void }) {
  const q = useQuery({
    queryKey: ["providers", id, "preview"],
    queryFn: () => previewObligations(id),
  });
  const m = useAct((_: void) => activateProvider(id), {
    success: "Provider activated",
    refresh: ["providers", "obligations"],
    onDone,
  });
  return (
    <div className="space-y-4">
      <View q={q}>
        {(d) => (
          <Card padded={false}>
            <Tbl head={["Activity", "Scope", "Opens", "Due"]}>
              {d.map((o) => (
                <tr key={o.id}>
                  <td>{o.activity.name}</td>
                  <td>{o.scopeLabel}</td>
                  <td>
                    <DateText value={o.openDate} />
                  </td>
                  <td>
                    <DateText value={o.dueDate} />
                  </td>
                </tr>
              ))}
            </Tbl>
          </Card>
        )}
      </View>
      <p className="text-[13px] text-muted-foreground">
        Class obligations are added when classes are scheduled.
      </p>
      <div className="flex justify-end gap-2">
        <Button variant="outline" onClick={onDone}>
          Later
        </Button>
        <Button disabled={m.isPending} onClick={() => m.mutate()}>
          Activate provider
        </Button>
      </div>
    </div>
  );
}
