import { createFileRoute, Link } from "@tanstack/react-router";
import { useQuery } from "@tanstack/react-query";
import {
  CartesianGrid,
  Line,
  LineChart,
  ReferenceLine,
  ResponsiveContainer,
  Tooltip,
  XAxis,
  YAxis,
} from "recharts";
import { Card, DateText, PageHeader } from "@/components/pbps/page";
import { ActionButton } from "@/components/pbps/action";
import { Dl, Tbl, View } from "@/components/pbps/blocks";
import { DetailSkeleton } from "@/components/pbps/states";
import { StatusBadge } from "@/components/pbps/status-badge";
import { Button } from "@/components/ui/button";
import { approveIndicatorVersion, getIndicator, retireIndicator } from "@/api/programme";
import { Can } from "@/lib/access";
import { fmtDate, fmtInt, fmtPct } from "@/lib/format";
import { P } from "@/lib/roles";

export const Route = createFileRoute("/p/$pid/indicators/$code/")({ component: Page });
function Page() {
  const { pid, code } = Route.useParams();
  const nav = Route.useNavigate();
  const q = useQuery({ queryKey: ["indicators", code], queryFn: () => getIndicator(code) });
  return (
    <View q={q} skeleton={<DetailSkeleton />}>
      {(d) => {
        const i = d.indicator;
        const f = (v?: number) => (i.unit === "%" ? fmtPct(v) : fmtInt(v));
        return (
          <>
            <PageHeader
              title={i.no ? `${i.no}. ${i.name}` : i.name}
              description={`Version ${i.version}, in effect since ${fmtDate(i.effectiveFrom)}`}
              actions={
                <>
                  <StatusBadge
                    size="md"
                    status={d.total.status}
                    label={`Project ${f(d.total.value)} of ${f(d.total.target)}`}
                  />
                  <Can perm={P.indicatorManage}>
                    <Button variant="outline" asChild>
                      <Link to="/p/$pid/indicators/$code/propose" params={{ pid, code }}>
                        Propose new version
                      </Link>
                    </Button>
                  </Can>
                  {i.no === 0 && (
                    <Can perm={P.indicatorManage}>
                      <ActionButton
                        size="default"
                        label="Retire"
                        title="Retire this indicator?"
                        description="It is no longer calculated. Its values and versions are kept."
                        run={() => retireIndicator(code)}
                        success="Indicator retired"
                        refresh={["indicators", "kpi", "dashboard", "targets"]}
                        confirmLabel="Retire"
                        destructive
                        onDone={() => void nav({ to: "/p/$pid/indicators", params: { pid } })}
                      />
                    </Can>
                  )}
                  <Can perm={P.targetManage}>
                    <Button variant="outline" asChild>
                      <Link to="/p/$pid/targets" params={{ pid }}>
                        Edit targets
                      </Link>
                    </Button>
                  </Can>
                </>
              }
            />
            <div className="space-y-5">
              <Card title="Protocol definition">
                <Dl
                  cols={2}
                  items={[
                    ["Operational definition", i.operationalDefinition],
                    ["Data sources", i.dataSources],
                    ["Numerator", i.numeratorLabel],
                    ["Denominator", i.denominatorLabel ?? "None (a number)"],
                    ["Computation", i.computation],
                    ["Frequency", i.frequency],
                    ["Verification method", i.verificationMethod],
                    ["Disaggregated by", i.disaggregations.join(", ").replace(/_/g, " ")],
                    [
                      "Default target",
                      `${i.comparator === "<=" ? "≤" : "≥"} ${f(i.defaultTarget)}`,
                    ],
                    ["Payment linkage", i.paymentLinkage ?? "None"],
                  ]}
                />
              </Card>
              <Card title="Results by provider" padded={false}>
                <Tbl
                  head={[
                    "Provider",
                    ">Monitoring",
                    ">Verified",
                    ">Target",
                    "Target source",
                    ">Numerator / denominator",
                    "Status",
                    "Note",
                  ]}
                >
                  {d.rows.map((r) => (
                    <tr key={r.providerId}>
                      <td className="font-medium">{r.providerName}</td>
                      <td className="text-right">{f(r.value)}</td>
                      <td className="text-right">{f(r.verified)}</td>
                      <td className="text-right">{f(r.target)}</td>
                      <td className="capitalize">{r.targetSource.replace("_", " ")}</td>
                      <td className="text-right">
                        {r.numerator === undefined
                          ? "—"
                          : `${fmtInt(r.numerator)} / ${fmtInt(r.denominator)}`}
                      </td>
                      <td>
                        <StatusBadge status={r.status} />
                      </td>
                      <td className="text-muted-foreground">{r.note}</td>
                    </tr>
                  ))}
                </Tbl>
              </Card>
              <div className="grid gap-5 lg:grid-cols-2">
                {d.trend.length > 1 && (
                  <Card title="Trend">
                    <div className="h-56">
                      <ResponsiveContainer>
                        <LineChart data={d.trend}>
                          <CartesianGrid vertical={false} stroke="var(--border)" />
                          <XAxis dataKey="date" fontSize={11} tickFormatter={fmtDate} />
                          <YAxis fontSize={11} domain={["auto", "auto"]} />
                          <Tooltip formatter={(v) => f(Number(v))} />
                          {d.total.target !== undefined && (
                            <ReferenceLine
                              y={d.total.target}
                              stroke="var(--amber)"
                              strokeDasharray="5 4"
                            />
                          )}
                          <Line
                            dataKey="value"
                            name={i.name}
                            stroke="var(--chart-1)"
                            strokeWidth={2}
                            dot={false}
                          />
                        </LineChart>
                      </ResponsiveContainer>
                    </div>
                  </Card>
                )}
                {d.disaggregation.map((g) => (
                  <Card key={g.dimension} title={`By ${g.dimension.toLowerCase()}`} padded={false}>
                    <Tbl head={[g.dimension, ">Value"]}>
                      {g.items.map((x) => (
                        <tr key={x.label}>
                          <td>{x.label}</td>
                          <td className="text-right font-semibold">{f(x.value)}</td>
                        </tr>
                      ))}
                    </Tbl>
                  </Card>
                ))}
              </div>
              <Card title="Versions" padded={false}>
                <Tbl head={[">Version", "Status", "In effect from", "Change", "Approved by"]}>
                  {d.versions.map((v) => (
                    <tr key={v.version}>
                      <td className="text-right">{v.version}</td>
                      <td>
                        <StatusBadge status={v.status} />
                      </td>
                      <td>
                        <DateText value={v.effectiveFrom} />
                      </td>
                      <td>{v.changeNote}</td>
                      <td>
                        {v.approvedBy ?? "—"}
                        {v.status === "draft" && (
                          <Can perm={P.indicatorManage}>
                            <ActionButton
                              label="Approve"
                              title={`Approve version ${v.version}?`}
                              description="It replaces the version in use. The old version is kept."
                              run={() => approveIndicatorVersion(code, v.version)}
                              success="Version approved"
                              refresh={["indicators", "kpi", "dashboard", "targets"]}
                              confirmLabel="Approve"
                            />
                          </Can>
                        )}
                      </td>
                    </tr>
                  ))}
                </Tbl>
              </Card>
            </div>
          </>
        );
      }}
    </View>
  );
}
