import { createFileRoute, useNavigate } from "@tanstack/react-router";
import { useQuery } from "@tanstack/react-query";
import { useState } from "react";
import { Card, PageHeader, Stat } from "@/components/pbps/page";
import { Field, FormError, Select, TextInput, YesNo } from "@/components/pbps/form";
import { Tbl, useAct, View } from "@/components/pbps/blocks";
import { Button } from "@/components/ui/button";
import { fieldErrorMap } from "@/api/client";
import { listProviderOptions } from "@/api/programme";
import { createRun, getSamplePreview, listPlans, listStages } from "@/api/verification";
import { fmtInt } from "@/lib/format";

export const Route = createFileRoute("/p/$pid/verification/new")({ component: Page });
function Page() {
  const { pid } = Route.useParams();
  const navigate = useNavigate();
  const [f, setF] = useState({
    indicator: "",
    providerId: "",
    period: new Date().toISOString().slice(0, 7),
    seed: "",
    stage: "",
  });
  const [pre, setPre] = useState<boolean>();
  const set = (k: keyof typeof f) => (v: string) => setF((s) => ({ ...s, [k]: v }));
  const plans = useQuery({ queryKey: ["verification", "plans"], queryFn: listPlans });
  const provs = useQuery({ queryKey: ["providers", "options"], queryFn: listProviderOptions });
  const all = useQuery({ queryKey: ["verification", "stages"], queryFn: listStages });
  const stages = (all.data ?? []).filter((x) => x.indicatorCode === f.indicator);
  const ready = !!f.indicator && !!f.providerId && (!stages.length || !!f.stage);
  const pv = useQuery({
    queryKey: ["verification", "preview", f.indicator, f.providerId, f.stage],
    queryFn: () =>
      getSamplePreview({
        indicator: f.indicator,
        providerId: f.providerId,
        ...(f.stage ? { stage: f.stage } : {}),
      }),
    enabled: ready,
  });
  const m = useAct(
    (_: void) =>
      createRun({
        indicator: f.indicator,
        providerId: f.providerId,
        period: f.period,
        ...(stages.length ? { stage: f.stage } : {}),
        ...(f.seed ? { seed: f.seed } : {}),
        ...(pre ? { preReport: true } : {}),
      }),
    {
      refresh: ["verification"],
      onError: () => {},
      onDone: (x) =>
        void navigate({ to: "/p/$pid/verification/runs/$id", params: { pid, id: x.runId } }),
    },
  );
  const err = fieldErrorMap(m.error);
  const blocked =
    !pv.data || pv.data.population === 0 || (!pv.data.reportsSubmitted && pre !== true);
  return (
    <>
      <PageHeader
        title="New verification run"
        description="Check the population and sample, then draw. The frame is frozen at the draw."
      />
      <div className="max-w-4xl space-y-5">
        <FormError error={m.error} />
        <Card title="What to verify">
          <div className="grid gap-4 sm:grid-cols-2">
            <Field label="Indicator" required>
              <Select
                value={f.indicator}
                onChange={(v) => setF((x) => ({ ...x, indicator: v, stage: "" }))}
                options={(plans.data ?? [])
                  .filter((p) => p.status === "active")
                  .map((p) => [p.indicatorCode, p.indicatorName])}
              />
            </Field>
            {stages.length > 0 && (
              <Field label="Stage" required error={err["stage"]}>
                <Select
                  value={f.stage}
                  onChange={set("stage")}
                  options={stages.map((x): [string, string] => [x.stageKey, x.label])}
                />
              </Field>
            )}
            <Field label="Provider" required>
              <Select
                value={f.providerId}
                onChange={set("providerId")}
                options={(provs.data ?? []).map((p) => [p.id, p.name])}
              />
            </Field>
            <Field label="Period" required error={err["period"]}>
              <TextInput type="month" value={f.period} onChange={set("period")} />
            </Field>
            <Field
              label="Seed"
              help="Leave empty to generate one. It is stored so the draw can be repeated."
            >
              <TextInput value={f.seed} onChange={set("seed")} />
            </Field>
          </div>
        </Card>
        {ready && (
          <View q={pv}>
            {(d) => (
              <>
                <div className="grid gap-3 sm:grid-cols-5">
                  <Stat label="Population" value={fmtInt(d.population)} />
                  <Stat label="Base sample (n₀)" value={d.n0} />
                  <Stat label="After population correction" value={d.nFpc} />
                  <Stat label="To draw" value={d.nTarget} />
                  <Stat label="Reserves" value={d.reserves} />
                </div>
                {d.warnings.length > 0 && (
                  <div role="status" className="rounded-lg bg-warning-soft p-3 text-[13px]">
                    {d.warnings.map((w) => (
                      <p key={w}>{w}</p>
                    ))}
                  </div>
                )}
                {!d.reportsSubmitted && (
                  <Card>
                    <Field
                      label="Draw before all reports are submitted?"
                      required
                      help="Only for indicators that sample all registered trainees."
                    >
                      <YesNo name="pre" value={pre} onChange={setPre} />
                    </Field>
                  </Card>
                )}
                <Card title="Strata" padded={false}>
                  <Tbl head={["Location", "Sex", ">Population", ">Primary", ">Reserve"]}>
                    {d.strata.map((s) => (
                      <tr key={s.location + s.sex}>
                        <td>{s.location}</td>
                        <td className="capitalize">{s.sex}</td>
                        <td className="text-right">{s.population}</td>
                        <td className="text-right">{s.primary}</td>
                        <td className="text-right">{s.reserve}</td>
                      </tr>
                    ))}
                  </Tbl>
                </Card>
              </>
            )}
          </View>
        )}
        <div className="flex justify-end">
          <Button
            disabled={!ready || !f.period || blocked || m.isPending}
            onClick={() => m.mutate()}
          >
            {m.isPending ? "Starting…" : "Draw sample"}
          </Button>
        </div>
      </div>
    </>
  );
}
