import { createFileRoute } from "@tanstack/react-router";
import { useQuery } from "@tanstack/react-query";
import { useState } from "react";
import { Card, PageHeader } from "@/components/pbps/page";
import { Field, FormError, Segmented, Select, TextInput } from "@/components/pbps/form";
import { SubNav, Tbl, useAct, View } from "@/components/pbps/blocks";
import { StatusBadge } from "@/components/pbps/status-badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { listPlans, savePlan } from "@/api/verification";
import type { VerificationPlan } from "@/api/types-extra";
import { useCan } from "@/lib/access";
import { P } from "@/lib/roles";
import { VERIFICATION_NAV } from "@/lib/sections";

export const Route = createFileRoute("/p/$pid/verification/plans")({ component: Page });
const EST: [VerificationPlan["estimator"], string][] = [
  ["wilson_one_sided", "Wilson, one-sided"],
  ["wilson_two_sided", "Wilson, two-sided"],
  ["clopper_pearson", "Clopper-Pearson"],
  ["simple_rate", "Simple rate"],
];
function Page() {
  const { pid } = Route.useParams();
  const can = useCan(P.verPlan);
  const [edit, setEdit] = useState<VerificationPlan>();
  const q = useQuery({ queryKey: ["verification", "plans"], queryFn: listPlans });
  return (
    <>
      <PageHeader
        title="Verification plans"
        description="How each indicator is sampled and judged. Saving creates a new version."
      />
      <SubNav pid={pid} items={VERIFICATION_NAV} />
      {edit ? (
        <Edit key={edit.id} p={edit} onClose={() => setEdit(undefined)} />
      ) : (
        <View q={q}>
          {(d) => (
            <Card padded={false}>
              <Tbl
                head={[
                  "Indicator",
                  ">Version",
                  "Status",
                  "Tiers",
                  "Estimator",
                  ">Margin",
                  ">Reserve",
                  "Sampled from",
                  "",
                ]}
              >
                {d.map((p) => (
                  <tr
                    key={`${p.id}-${p.version}`}
                    className={p.status === "retired" ? "text-muted-foreground" : ""}
                  >
                    <td className="font-medium">{p.indicatorName}</td>
                    <td className="text-right">{p.version}</td>
                    <td>
                      <StatusBadge status={p.status} />
                    </td>
                    <td>{p.tiering === "single" ? "Single" : "Two-tier"}</td>
                    <td>{EST.find(([k]) => k === p.estimator)?.[1]}</td>
                    <td className="text-right">{p.e}</td>
                    <td className="text-right">{p.reservePct} %</td>
                    <td>{POP.find(([k]) => k === p.populationMetric)?.[1]}</td>
                    <td className="text-right">
                      {can && p.status === "active" && (
                        <Button size="sm" variant="ghost" onClick={() => setEdit(p)}>
                          Edit
                        </Button>
                      )}
                    </td>
                  </tr>
                ))}
              </Tbl>
            </Card>
          )}
        </View>
      )}
    </>
  );
}
const POP: [string, string][] = [
  ["trainees.registered", "All registered trainees"],
  ["trainees.base", "Trainees who passed the report before"],
  ["trainees.claimed", "Trainees reported as Yes"],
];
const NUM = [
  ["z", "Z", 0.5, 4],
  ["p", "Expected proportion (p)", 0.01, 0.99],
  ["e", "Margin of error (e)", 0.001, 0.49],
  ["nonResponse", "Expected response (0–1)", 0.1, 1],
  ["reservePct", "Reserve (%)", 0, 100],
  ["minPerStratum", "Minimum per stratum", 0, 100],
  ["ciZ", "Confidence interval z", 0.5, 4],
] as const;
function Edit({ p, onClose }: { p: VerificationPlan; onClose: () => void }) {
  const [n, setN] = useState<Record<string, string>>(
    Object.fromEntries(NUM.map(([k]) => [k, String(p[k])])),
  );
  const [f, setF] = useState({
    tiering: p.tiering,
    estimator: p.estimator,
    decisionRule: p.decisionRule,
    populationMetric: p.populationMetric,
    effectiveFrom: new Date().toISOString().slice(0, 10),
  });
  const v = (k: string) => Number(n[k]);
  const err = Object.fromEntries(
    NUM.filter(([k, , lo, hi]) => !n[k]?.trim() || !(v(k) >= lo && v(k) <= hi)).map(
      ([k, , lo, hi]) => [k, `Enter ${lo} to ${hi}.`],
    ),
  );
  const ok = !Object.keys(err).length;
  const N = 1040;
  const n0 = Math.ceil((v("z") ** 2 * v("p") * (1 - v("p"))) / v("e") ** 2);
  const nf = Math.ceil(n0 / (1 + (n0 - 1) / N));
  const nt = Math.min(N, Math.ceil(nf / v("nonResponse")));
  const m = useAct(
    (_: void) =>
      savePlan({
        indicatorCode: p.indicatorCode,
        indicatorName: p.indicatorName,
        strata: p.strata,
        ...f,
        z: v("z"),
        p: v("p"),
        e: v("e"),
        nonResponse: v("nonResponse"),
        reservePct: v("reservePct"),
        minPerStratum: v("minPerStratum"),
        ciZ: v("ciZ"),
      }),
    {
      success: (r) => `Version ${r.version} saved`,
      refresh: ["verification"],
      onError: () => {},
      onDone: onClose,
    },
  );
  return (
    <Card title={`${p.indicatorName}: new version`} className="max-w-3xl">
      <FormError error={m.error} />
      <div className="grid gap-4 sm:grid-cols-2">
        <Field label="Population">
          <Select
            value={f.populationMetric}
            onChange={(x) => x && setF((s) => ({ ...s, populationMetric: x }))}
            options={POP}
          />
        </Field>
        <Field label="Tiers">
          <Segmented
            value={f.tiering}
            onChange={(x) => setF((s) => ({ ...s, tiering: x }))}
            options={[
              ["single", "Single"],
              ["two_tier", "Two-tier"],
            ]}
          />
        </Field>
        <Field label="Estimator">
          <Select
            value={f.estimator}
            onChange={(x) =>
              x && setF((s) => ({ ...s, estimator: x as VerificationPlan["estimator"] }))
            }
            options={EST}
          />
        </Field>
        <Field label="Decision rule">
          <Segmented
            value={f.decisionRule}
            onChange={(x) => setF((s) => ({ ...s, decisionRule: x }))}
            options={[
              ["ci_vs_target", "Interval vs target"],
              ["point_vs_target", "Rate vs target"],
            ]}
          />
        </Field>
        {NUM.map(([k, l]) => (
          <Field key={k} label={l} required error={err[k]}>
            <TextInput
              inputMode="decimal"
              value={n[k] ?? ""}
              onChange={(x) => setN((s) => ({ ...s, [k]: x }))}
            />
          </Field>
        ))}
        <Field label="In effect from" required>
          <Input
            type="date"
            value={f.effectiveFrom}
            onChange={(e) => setF((s) => ({ ...s, effectiveFrom: e.target.value }))}
          />
        </Field>
      </div>
      {ok && (
        <p className="mt-4 rounded-lg bg-surface-2 p-3 text-[13px]">
          Example, population {N}: base sample {n0}, after population correction {nf}, to draw {nt},
          reserves {Math.ceil((nt * v("reservePct")) / 100)}.
        </p>
      )}
      <div className="mt-4 flex justify-end gap-2">
        <Button variant="outline" onClick={onClose}>
          Cancel
        </Button>
        <Button disabled={!ok || !f.effectiveFrom || m.isPending} onClick={() => m.mutate()}>
          Save new version
        </Button>
      </div>
    </Card>
  );
}
