import { createFileRoute, useNavigate } from "@tanstack/react-router";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useState } from "react";
import { toast } from "sonner";
import { Card, PageHeader } from "@/components/pbps/page";
import {
  Field,
  FormError,
  Segmented,
  Select,
  TextArea,
  TextInput,
  WeekdayPicker,
} from "@/components/pbps/form";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { createTraining } from "@/api/delivery";
import { listLocations } from "@/api/admin";
import { listProviderOptions } from "@/api/programme";
import { fieldErrorMap } from "@/api/client";
import { useAccess } from "@/lib/access";
import { addDays } from "@/lib/dates";
import { isTpRole } from "@/lib/roles";
import { useUnsavedChangesPrompt } from "@/lib/hooks";

export const Route = createFileRoute("/p/$pid/trainings/new")({ component: Page });
const DUR = { basic: 3, intermediate: 4, advanced: 6 } as const;

function Page() {
  const { pid } = Route.useParams();
  const navigate = useNavigate();
  const qc = useQueryClient();
  const { access } = useAccess();
  const tp = access ? isTpRole(access.roleCode) : false;
  const provs = useQuery({
    queryKey: ["providers", "options"],
    queryFn: listProviderOptions,
    enabled: !tp,
  });
  const [f, setF] = useState({
    providerId: access?.providerId ?? "",
    title: "",
    programmeName: "",
    level: "" as "" | keyof typeof DUR,
    durationMonths: 0 as 0 | 3 | 4 | 6,
    plannedStart: "",
    plannedEnd: "",
    weekdays: [1, 2, 3, 4, 5],
    locationCodes: [] as string[],
    description: "",
  });
  const locs = useQuery({ queryKey: ["locations"], queryFn: listLocations });
  const set = <K extends keyof typeof f>(k: K, v: (typeof f)[K]) => setF((s) => ({ ...s, [k]: v }));
  const [errs, setErrs] = useState<Record<string, string>>({});
  const dirty = !!(f.title || f.plannedStart);
  useUnsavedChangesPrompt(dirty);
  const m = useMutation({
    mutationFn: () =>
      createTraining({
        providerId: f.providerId,
        title: f.title.trim(),
        ...(f.programmeName ? { programmeName: f.programmeName } : {}),
        level: f.level as keyof typeof DUR,
        durationMonths: (f.durationMonths || 4) as 3 | 4 | 6,
        plannedStart: f.plannedStart,
        plannedEnd: f.plannedEnd,
        weekdays: f.weekdays,
        locationCodes: f.locationCodes,
        ...(f.description ? { description: f.description } : {}),
      }),
    onSuccess: (t) => {
      toast.success("Training created — now add classes per site");
      void qc.invalidateQueries({ queryKey: ["trainings"] });
      setF((s) => ({ ...s, title: "", plannedStart: "" }));
      void navigate({ to: "/p/$pid/trainings/$id", params: { pid, id: t.id } });
    },
    onError: (e) => setErrs(fieldErrorMap(e)),
  });
  const submit = () => {
    const e: Record<string, string> = {};
    if (!f.providerId) e["providerId"] = "Choose a provider.";
    if (!f.title.trim()) e["title"] = "Title is required.";
    if (!f.level) e["level"] = "Choose a level.";
    if (!f.plannedStart) e["plannedStart"] = "Start date is required.";
    if (!f.plannedEnd || f.plannedEnd < f.plannedStart)
      e["plannedEnd"] = "End must be after start.";
    if (!f.weekdays.length) e["weekdays"] = "Choose at least one weekday.";
    if (!f.locationCodes.length) e["locationCodes"] = "Choose at least one site.";
    setErrs(e);
    if (!Object.keys(e).length) m.mutate();
  };
  const durWarn =
    f.plannedStart &&
    f.plannedEnd &&
    f.durationMonths &&
    Math.abs(
      (Date.parse(f.plannedEnd) - Date.parse(f.plannedStart)) / 864e5 - f.durationMonths * 30.4,
    ) >
      f.durationMonths * 3;
  return (
    <>
      <PageHeader
        title="New training"
        description="A course delivered under the provider's contract. Classes (with their own dates, weekdays and shift) are added per site after saving."
      />
      <Card className="max-w-3xl">
        <FormError error={m.error} />
        <form
          className="grid gap-4 sm:grid-cols-2"
          onSubmit={(e) => {
            e.preventDefault();
            submit();
          }}
        >
          {!tp && (
            <Field
              label="Training provider"
              required
              error={errs["providerId"]}
              className="sm:col-span-2"
            >
              <Select
                value={f.providerId}
                onChange={(v) => set("providerId", v)}
                options={(provs.data ?? []).map((p) => [p.id, `${p.code} · ${p.name}`])}
                error={errs["providerId"]}
              />
            </Field>
          )}
          <Field label="Training title" required error={errs["title"]} className="sm:col-span-2">
            <TextInput
              value={f.title}
              onChange={(v) => set("title", v)}
              placeholder="e.g. Full-Stack Web Development"
              error={errs["title"]}
            />
          </Field>
          <Field
            label="Programme name"
            help="Optional — the name used in the contract, if different."
          >
            <TextInput value={f.programmeName} onChange={(v) => set("programmeName", v)} />
          </Field>
          <Field label="Level" required error={errs["level"]}>
            <Segmented
              value={f.level || undefined}
              onChange={(v) =>
                setF((s) => ({
                  ...s,
                  level: v,
                  durationMonths: DUR[v],
                  ...(s.plannedStart ? { plannedEnd: addDays(s.plannedStart, DUR[v] * 30) } : {}),
                }))
              }
              options={[
                ["basic", "Basic"],
                ["intermediate", "Intermediate"],
                ["advanced", "Advanced"],
              ]}
            />
          </Field>
          <Field
            label="Duration"
            help="Set from the level; change only if the contract says otherwise."
          >
            <Segmented
              value={f.durationMonths ? (String(f.durationMonths) as "3") : undefined}
              onChange={(v) => set("durationMonths", Number(v) as 3)}
              options={[
                ["3", "3 months"],
                ["4", "4 months"],
                ["6", "6 months"],
              ]}
            />
          </Field>
          <Field label="Planned start" required error={errs["plannedStart"]}>
            <Input
              type="date"
              value={f.plannedStart}
              onChange={(e) =>
                setF((s) => ({
                  ...s,
                  plannedStart: e.target.value,
                  ...(s.durationMonths && e.target.value
                    ? { plannedEnd: addDays(e.target.value, s.durationMonths * 30) }
                    : {}),
                }))
              }
            />
          </Field>
          <Field
            label="Planned end"
            required
            error={errs["plannedEnd"]}
            help={
              durWarn
                ? "⚠ The window does not match the duration — check the dates."
                : "Suggested from the duration."
            }
          >
            <Input
              type="date"
              value={f.plannedEnd}
              onChange={(e) => set("plannedEnd", e.target.value)}
            />
          </Field>
          <Field
            label="Default session weekdays"
            error={errs["weekdays"]}
            help="Classes can override this."
            className="sm:col-span-2"
          >
            <WeekdayPicker
              value={f.weekdays}
              onChange={(v) => set("weekdays", v)}
              error={errs["weekdays"]}
            />
          </Field>
          <Field
            label="Delivery sites"
            required
            error={errs["locationCodes"]}
            className="sm:col-span-2"
          >
            <div className="flex flex-wrap gap-2">
              {(locs.data ?? [])
                .filter((l) => l.active)
                .map((l) => [l.code, l.name])
                .map(([c, n]) => {
                  const on = f.locationCodes.includes(c!);
                  return (
                    <button
                      key={c}
                      type="button"
                      aria-pressed={on}
                      onClick={() =>
                        set(
                          "locationCodes",
                          on ? f.locationCodes.filter((x) => x !== c) : [...f.locationCodes, c!],
                        )
                      }
                      className={`rounded-md border px-3 py-1.5 text-[13px] ${on ? "border-primary bg-primary text-primary-foreground" : "bg-card hover:bg-surface-2"}`}
                    >
                      {n}
                    </button>
                  );
                })}
            </div>
          </Field>
          <Field label="Description" className="sm:col-span-2">
            <TextArea
              value={f.description}
              onChange={(v) => set("description", v)}
              maxLength={1000}
            />
          </Field>
          <div className="flex justify-end gap-2 sm:col-span-2">
            <Button
              type="button"
              variant="outline"
              onClick={() => void navigate({ to: "/p/$pid/trainings", params: { pid } })}
            >
              Cancel
            </Button>
            <Button type="submit" disabled={m.isPending}>
              {m.isPending ? "Saving…" : "Save training"}
            </Button>
          </div>
        </form>
      </Card>
    </>
  );
}
