import { createFileRoute, Link, useNavigate } from "@tanstack/react-router";
import { ExportMenu } from "@/components/pbps/export-menu";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useState } from "react";
import { toast } from "sonner";
import { Card, DateText, Mono, PageHeader, PhoneText, Stat } from "@/components/pbps/page";
import {
  DetailSkeleton,
  EmptyState,
  ErrorState,
  KpiGridSkeleton,
  TableSkeleton,
} from "@/components/pbps/states";
import { StatusBadge } from "@/components/pbps/status-badge";
import { KpiCard, ProgressRing, TargetBar } from "@/components/pbps/kpi";
import { DataTable } from "@/components/pbps/data-table";
import { JobProgress } from "@/components/pbps/job-progress";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { fmtInt, fmtPct, relativeTime } from "@/lib/format";
import { useAccess, useCan } from "@/lib/access";
import { cn } from "@/lib/utils";

import { getKpiMatrix } from "@/api/programme";
import { ShieldCheck } from "lucide-react";
export const Route = createFileRoute("/p/$pid/kpi-report")({ component: Page });
function Page() {
  const [layer, setLayer] = useState<"monitoring" | "verified" | "both">("monitoring");
  const q = useQuery({
    queryKey: ["kpi", "matrix"],
    queryFn: () => getKpiMatrix(),
    staleTime: 60000,
  });
  const f = (v: number | undefined, u: string) => (u === "%" ? fmtPct(v) : fmtInt(v));
  return (
    <>
      <PageHeader
        title="KPI report"
        description="Every provider against its own targets."
        actions={
          <>
            <div className="flex rounded-md border">
              {(["monitoring", "verified", "both"] as const).map((l) => (
                <button
                  key={l}
                  type="button"
                  onClick={() => setLayer(l)}
                  className={cn(
                    "px-3 py-1.5 text-[13px] capitalize",
                    layer === l && "bg-primary text-primary-foreground",
                  )}
                >
                  {l}
                </button>
              ))}
            </div>
            <ExportMenu report="indicators_summary" formats={["pdf", "docx", "xlsx", "csv"]} />
          </>
        }
      />
      {q.isPending ? (
        <TableSkeleton cols={10} />
      ) : q.isError ? (
        <ErrorState error={q.error} />
      ) : (
        <Card padded={false}>
          <div className="overflow-x-auto">
            <table className="text-[12px] tabular">
              <thead className="bg-surface-2 text-muted-foreground">
                <tr>
                  <th className="sticky left-0 bg-surface-2 px-4 py-2 text-left">Provider</th>
                  {q.data.indicators.map((i) => (
                    <th
                      key={i.code}
                      className="min-w-40 px-2 py-2 text-right align-bottom font-medium whitespace-normal"
                      title={i.definition}
                    >
                      #{i.no} {i.label}
                    </th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {q.data.rows.map((r) => (
                  <tr key={r.provider.id} className="border-t">
                    <td className="sticky left-0 bg-card px-4 py-2 font-medium">
                      {r.provider.code}
                    </td>
                    {r.cells.map((c, i) => {
                      const u = q.data.indicators[i]?.unit ?? "%";
                      // One provider either did the activity or not.
                      const yesNo = q.data.indicators[i]?.level === "provider";
                      return (
                        <td
                          key={c.indicatorCode}
                          className={cn(
                            "px-2 py-2 text-right",
                            layer !== "verified" &&
                              c.status === "met" &&
                              "bg-success-soft text-success",
                            layer !== "verified" &&
                              c.status === "not_met" &&
                              "bg-danger-soft text-danger",
                          )}
                        >
                          {layer !== "verified" &&
                            (yesNo ? (c.value ? "Yes" : "No") : f(c.value, u))}
                          {layer !== "monitoring" && (
                            <span className="block text-success">
                              {c.verified !== undefined ? (
                                <>
                                  <ShieldCheck className="inline h-3 w-3" /> {f(c.verified, u)}
                                </>
                              ) : (
                                <span className="text-subtle">—</span>
                              )}
                            </span>
                          )}
                        </td>
                      );
                    })}
                  </tr>
                ))}
                <tr className="border-t bg-surface-2 font-semibold">
                  <td className="sticky left-0 bg-surface-2 px-4 py-2">Project</td>
                  {q.data.totals.map((t, i) => (
                    <td key={t.indicatorCode} className="px-2 py-2 text-right">
                      {f(t.value, q.data.indicators[i]?.unit ?? "%")}
                    </td>
                  ))}
                </tr>
              </tbody>
            </table>
          </div>
        </Card>
      )}
    </>
  );
}
