import { createFileRoute, Link } from "@tanstack/react-router";
import { useQuery } from "@tanstack/react-query";
import { useState } from "react";
import { ExportMenu } from "@/components/pbps/export-menu";
import { Select } from "@/components/pbps/form";
import { Button } from "@/components/ui/button";
import { listProviderOptions } from "@/api/programme";
import { useAccess } from "@/lib/access";
import {
  Bar,
  BarChart,
  CartesianGrid,
  Legend,
  Line,
  LineChart,
  ReferenceLine,
  ResponsiveContainer,
  Tooltip,
  XAxis,
  YAxis,
} from "recharts";
import { Card, PageHeader } from "@/components/pbps/page";
import { SubNav, Tbl, View } from "@/components/pbps/blocks";
import { TargetBar } from "@/components/pbps/kpi";
import { getAttendanceInsights, getCoverage, type CoverageRow } from "@/api/attendance";
import { fmtDate, fmtPct } from "@/lib/format";
import { cn } from "@/lib/utils";
import { ATTENDANCE_NAV } from "@/lib/sections";

export const Route = createFileRoute("/p/$pid/attendance/insights")({ component: Page });
function Page() {
  const { pid } = Route.useParams();
  const q = useQuery({
    queryKey: ["attendance", "insights"],
    queryFn: () => getAttendanceInsights(),
    staleTime: 60_000,
  });
  const tip = (v: unknown) => fmtPct(Number(v));
  return (
    <>
      <PageHeader title="Attendance insights" description="Rates against the 80 % threshold." />
      <SubNav pid={pid} items={ATTENDANCE_NAV} />
      <View q={q}>
        {(d) => (
          <div className="space-y-5">
            <div className="grid gap-5 lg:grid-cols-2">
              <Card title="Rate by provider">
                <div
                  className="h-64"
                  role="img"
                  aria-label={d.byProvider.map((p) => `${p.code} ${fmtPct(p.rate)}`).join(", ")}
                >
                  <ResponsiveContainer>
                    <BarChart data={d.byProvider}>
                      <CartesianGrid vertical={false} stroke="var(--border)" />
                      <XAxis dataKey="code" fontSize={11} />
                      <YAxis domain={[0, 100]} fontSize={11} />
                      <Tooltip formatter={tip} />
                      <ReferenceLine y={80} stroke="var(--danger)" strokeDasharray="5 4" />
                      <Bar dataKey="rate" name="Attendance" fill="var(--chart-1)" maxBarSize={48} />
                    </BarChart>
                  </ResponsiveContainer>
                </div>
              </Card>
              <Card title="Weekly trend">
                <div className="h-64">
                  <ResponsiveContainer>
                    <LineChart data={d.weekly}>
                      <CartesianGrid vertical={false} stroke="var(--border)" />
                      <XAxis dataKey="week" fontSize={11} tickFormatter={fmtDate} />
                      <YAxis domain={[50, 100]} fontSize={11} />
                      <Tooltip formatter={tip} />
                      <Legend />
                      <ReferenceLine y={80} stroke="var(--danger)" strokeDasharray="5 4" />
                      {d.series.map((s, i) => (
                        <Line
                          key={s}
                          dataKey={s}
                          stroke={`var(--chart-${(i % 5) + 1})`}
                          strokeWidth={2}
                          dot={false}
                        />
                      ))}
                    </LineChart>
                  </ResponsiveContainer>
                </div>
              </Card>
              {(
                [
                  ["By sex", d.bySex],
                  ["By site", d.byLocation],
                ] as const
              ).map(([t, rows]) => (
                <Card key={t} title={t}>
                  <div className="space-y-3">
                    {rows.map((r) => (
                      <div key={r.label}>
                        <div className="flex justify-between text-[13px]">
                          <span>{r.label}</span>
                          <b className="tabular">{fmtPct(r.rate)}</b>
                        </div>
                        <div className="mt-1">
                          <TargetBar value={r.rate} target={80} max={100} />
                        </div>
                      </div>
                    ))}
                  </div>
                </Card>
              ))}
            </div>
            <Coverage />
            <Card title="Coverage by class" padded={false}>
              <Tbl head={["Class", "Provider", ">Rate", ">Coverage", ">Missing sessions"]}>
                {d.byClass.map((c) => (
                  <tr key={c.id}>
                    <td>
                      <Link
                        className="font-mono text-primary hover:underline"
                        to="/p/$pid/classes/$id"
                        params={{ pid, id: c.id }}
                      >
                        {c.code}
                      </Link>
                    </td>
                    <td>{c.providerCode}</td>
                    <td className={cn("text-right", (c.rate ?? 100) < 80 && "text-danger")}>
                      {fmtPct(c.rate)}
                    </td>
                    <td className="text-right">{fmtPct(c.coverage)}</td>
                    <td className={cn("text-right", c.missing && "font-semibold text-danger")}>
                      {c.missing}
                    </td>
                  </tr>
                ))}
              </Tbl>
            </Card>
          </div>
        )}
      </View>
    </>
  );
}
const DIMS: [keyof CoverageRow, string][] = [
  ["location", "Location"],
  ["training", "Training"],
  ["site", "Site"],
  ["class", "Class"],
];
/** Session days recorded against due, per provider and any breakdown the reader asks for. */
function Coverage() {
  const { access } = useAccess();
  const [provider, setProvider] = useState("");
  const [dims, setDims] = useState<(keyof CoverageRow)[]>([]);
  const provs = useQuery({
    queryKey: ["providers", "options"],
    queryFn: listProviderOptions,
    enabled: !access?.providerId,
  });
  const q = useQuery({
    queryKey: ["attendance", "coverage", provider],
    queryFn: () => getCoverage(provider),
  });
  const use = DIMS.filter(([k]) => dims.includes(k));
  const rows = new Map<string, { keys: string[]; due: number; done: number }>();
  for (const x of q.data ?? []) {
    const keys = [x.providerName, ...use.map(([k]) => String(x[k]))];
    const id = JSON.stringify([x.provider, ...keys]);
    const g = rows.get(id) ?? { keys, due: 0, done: 0 };
    g.due += Number(x.due ?? 0);
    g.done += Number(x.submitted ?? 0);
    rows.set(id, g);
  }
  return (
    <Card
      title="Attendance coverage"
      padded={false}
      actions={
        <ExportMenu
          report="attendance_coverage"
          formats={["xlsx", "csv", "pdf", "docx"]}
          params={{ providerId: provider, dims: dims.join(",") }}
          perm="attendance.view"
        />
      }
    >
      <div className="flex flex-wrap items-center gap-2 border-b px-4 py-3 text-[13px]">
        {!access?.providerId && (
          <div className="w-56">
            <Select
              ariaLabel="Provider"
              placeholder="All providers"
              value={provider}
              onChange={setProvider}
              options={(provs.data ?? []).map((p): [string, string] => [p.id, p.name])}
            />
          </div>
        )}
        <span className="text-muted-foreground">Break down by</span>
        {DIMS.map(([k, l]) => (
          <Button
            key={k}
            size="sm"
            variant={dims.includes(k) ? "default" : "outline"}
            aria-pressed={dims.includes(k)}
            onClick={() => setDims(dims.includes(k) ? dims.filter((x) => x !== k) : [...dims, k])}
          >
            {l}
          </Button>
        ))}
      </div>
      <View q={q}>
        {() => (
          <div className="max-h-[480px] overflow-y-auto">
            <Tbl
              head={[
                "Provider",
                ...use.map(([, l]) => l),
                ">Recorded",
                ">Due",
                ">Missing",
                "Coverage",
              ]}
            >
              {[...rows.values()].map((g) => {
                const v = g.due ? (g.done / g.due) * 100 : 0;
                return (
                  <tr key={g.keys.join("|")}>
                    {g.keys.map((x, i) => (
                      <td key={i} className={i ? "" : "font-medium"}>
                        {x}
                      </td>
                    ))}
                    <td className="text-right">{g.done}</td>
                    <td className="text-right">{g.due}</td>
                    <td className={cn("text-right", g.due > g.done && "font-semibold text-danger")}>
                      {g.due - g.done}
                    </td>
                    <td className="min-w-40">
                      <span className="flex items-center gap-2">
                        <span className="h-2 flex-1 overflow-hidden rounded-full bg-surface-2">
                          <span
                            className={cn(
                              "block h-full",
                              v >= 100 ? "bg-success" : v >= 80 ? "bg-primary" : "bg-danger",
                            )}
                            style={{ width: `${v}%` }}
                          />
                        </span>
                        <b className="w-14 text-right tabular">{fmtPct(v)}</b>
                      </span>
                    </td>
                  </tr>
                );
              })}
            </Tbl>
          </div>
        )}
      </View>
    </Card>
  );
}
