import { createFileRoute } from "@tanstack/react-router";
import { useQuery } from "@tanstack/react-query";
import { useState } from "react";
import { Card, DateText, PageHeader } from "@/components/pbps/page";
import { Field, FileDropzone, FormError, TextInput } from "@/components/pbps/form";
import { DownloadButton, Tbl, useAct, View } from "@/components/pbps/blocks";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { ApiError } from "@/api/client";
import { proj } from "@/api/http";
import { importTargets, listTargets, setTarget } from "@/api/programme";
import type { Indicator } from "@/api/types";
import { useCan } from "@/lib/access";
import { shortIndicator } from "@/lib/indicators";
import { P } from "@/lib/roles";
import { cn } from "@/lib/utils";

export const Route = createFileRoute("/p/$pid/targets")({ component: Page });
interface Cell {
  ind: Indicator;
  providerId: string | null;
  provider: string;
  current: number;
}
function Page() {
  const can = useCan(P.targetManage);
  const [cell, setCell] = useState<Cell>();
  const [hist, setHist] = useState(false);
  const [imp, setImp] = useState(false);
  const q = useQuery({ queryKey: ["targets"], queryFn: listTargets });
  return (
    <>
      <PageHeader
        title="Targets"
        description="Each provider's target per indicator. Grey values use the project default. Past targets are kept."
        actions={
          <>
            {can && (
              <Button variant="outline" onClick={() => setImp(true)}>
                Import from Excel
              </Button>
            )}
            <Button variant="outline" onClick={() => setHist(!hist)}>
              {hist ? "Show grid" : "History"}
            </Button>
          </>
        }
      />
      <View q={q}>
        {(d) =>
          hist ? (
            <Card padded={false}>
              <Tbl head={["Indicator", "Provider", ">Target", "From", "Until", "Note", "Set by"]}>
                {[...d.history]
                  .sort((a, b) => b.effectiveFrom.localeCompare(a.effectiveFrom))
                  .map((h, i) => (
                    <tr key={i}>
                      <td>{shortIndicator(h.indicatorCode)}</td>
                      <td>
                        {d.providers.find((p) => p.id === h.providerId)?.name ?? "Project default"}
                      </td>
                      <td className="text-right font-semibold">{h.value}</td>
                      <td>
                        <DateText value={h.effectiveFrom} />
                      </td>
                      <td>{h.effectiveTo ? <DateText value={h.effectiveTo} /> : "Current"}</td>
                      <td>{h.note}</td>
                      <td>{h.setBy}</td>
                    </tr>
                  ))}
              </Tbl>
            </Card>
          ) : (
            <Card padded={false}>
              <div className="overflow-x-auto">
                <table className="w-full text-[13px] tabular">
                  <thead className="bg-surface-2 text-[12.5px] text-muted-foreground">
                    <tr>
                      <th scope="col" className="sticky left-0 bg-surface-2 px-4 py-2 text-left">
                        Indicator
                      </th>
                      <th scope="col" className="px-3 text-right">
                        Project default
                      </th>
                      {d.providers.map((p) => (
                        <th scope="col" key={p.id} title={p.name} className="px-3 text-right">
                          {p.code}
                        </th>
                      ))}
                    </tr>
                  </thead>
                  <tbody>
                    {d.indicators.map((i) => (
                      <tr key={i.code} className="border-t">
                        <th
                          scope="row"
                          className="sticky left-0 bg-card px-4 py-1 text-left font-medium"
                        >
                          {i.no}. {shortIndicator(i.code)}{" "}
                          <span className="font-normal text-muted-foreground">
                            ({i.direction === "lower_is_better" ? "≤" : "≥"} {i.unit})
                          </span>
                        </th>
                        <td className="px-3 text-right">{i.defaultTarget}</td>
                        {d.providers.map((p) => {
                          const own = d.cells[p.id]?.[i.code];
                          return (
                            <td key={p.id} className="px-1 text-right">
                              <button
                                type="button"
                                disabled={!can}
                                onClick={() =>
                                  setCell({
                                    ind: i,
                                    providerId: p.id,
                                    provider: p.name,
                                    current: own ?? i.defaultTarget,
                                  })
                                }
                                className={cn(
                                  "min-h-9 min-w-12 rounded px-2 text-right enabled:hover:bg-surface-2",
                                  own === undefined ? "text-muted-foreground" : "font-semibold",
                                )}
                              >
                                {own ?? i.defaultTarget}
                                <span className="sr-only">
                                  {own === undefined ? " (default)" : ""}, {p.name}
                                </span>
                              </button>
                            </td>
                          );
                        })}
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </Card>
          )
        }
      </View>
      {imp && <Import onClose={() => setImp(false)} />}
      {cell && <Edit c={cell} onClose={() => setCell(undefined)} />}
    </>
  );
}
function Edit({ c, onClose }: { c: Cell; onClose: () => void }) {
  const [v, setV] = useState(String(c.current));
  const [from, setFrom] = useState(new Date().toISOString().slice(0, 10));
  const [note, setNote] = useState("");
  const [err, setErr] = useState<Record<string, string>>({});
  const m = useAct(
    (_: void) =>
      setTarget({
        indicatorCode: c.ind.code,
        providerId: c.providerId,
        value: Number(v),
        effectiveFrom: from,
        note,
      }),
    {
      success: "Target saved",
      refresh: ["targets", "kpi", "providers", "indicators", "dashboard"],
      onDone: onClose,
    },
  );
  const save = () => {
    const e: Record<string, string> = {};
    const n = Number(v);
    if (!v.trim() || !Number.isFinite(n) || n < 0 || (c.ind.unit === "%" && n > 100))
      e["v"] = c.ind.unit === "%" ? "Enter 0 to 100." : "Enter a positive number.";
    if (!from) e["from"] = "Choose a date.";
    if (!note.trim()) e["note"] = "Say why the target is set or changed.";
    setErr(e);
    if (!Object.keys(e).length) m.mutate();
  };
  return (
    <Dialog
      open
      onOpenChange={(o) => {
        if (!o) onClose();
      }}
    >
      <DialogContent>
        <DialogHeader>
          <DialogTitle>
            {shortIndicator(c.ind.code)}: {c.provider}
          </DialogTitle>
        </DialogHeader>
        <form
          noValidate
          className="space-y-3"
          onSubmit={(e) => {
            e.preventDefault();
            save();
          }}
        >
          <Field label={`Target (${c.ind.unit})`} required error={err["v"]}>
            <TextInput inputMode="decimal" value={v} onChange={setV} />
          </Field>
          <Field label="In effect from" required error={err["from"]}>
            <Input type="date" value={from} onChange={(e) => setFrom(e.target.value)} />
          </Field>
          <Field label="Note" required error={err["note"]}>
            <TextInput value={note} onChange={setNote} maxLength={300} />
          </Field>
          <DialogFooter>
            <Button type="button" variant="outline" onClick={onClose}>
              Cancel
            </Button>
            <Button type="submit" disabled={m.isPending}>
              {m.isPending ? "Saving…" : "Save target"}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
function Import({ onClose }: { onClose: () => void }) {
  const [files, setFiles] = useState<File[]>([]);
  const m = useAct((f: File) => importTargets(f), {
    success: (x) => `${x.saved} targets saved, ${x.unchanged} unchanged`,
    refresh: ["targets", "kpi", "providers", "indicators", "dashboard"],
    onError: () => {},
    onDone: onClose,
  });
  const rows = m.error instanceof ApiError ? m.error.fieldErrors : [];
  return (
    <Dialog
      open
      onOpenChange={(o) => {
        if (!o) onClose();
      }}
    >
      <DialogContent>
        <DialogHeader>
          <DialogTitle>Import targets</DialogTitle>
        </DialogHeader>
        <p className="text-[13px]">
          Download the file, change the target column, and upload it. If one row is wrong, nothing
          is saved.
        </p>
        <div>
          <DownloadButton path={proj("/targets/template")}>Current targets</DownloadButton>
        </div>
        <FileDropzone accept={["xlsx", "csv"]} maxSizeMb={5} files={files} onFiles={setFiles} />
        <FormError error={m.error} />
        {rows.length > 0 && (
          <ul className="max-h-48 overflow-y-auto text-[13px]">
            {rows.map((x) => (
              <li key={x.path + x.message}>
                <b>{x.path}</b>: {x.message}
              </li>
            ))}
          </ul>
        )}
        <DialogFooter>
          <Button variant="outline" onClick={onClose}>
            Cancel
          </Button>
          <Button
            disabled={!files[0] || m.isPending}
            onClick={() => files[0] && m.mutate(files[0])}
          >
            {m.isPending ? "Checking…" : "Import"}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
