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 { fmtDate, fmtDateTime, fmtInt, fmtPct } from "@/lib/format";
import { shortIndicator } from "@/lib/indicators";
import { useAccess, useCan } from "@/lib/access";
import { cn } from "@/lib/utils";

import { startJob } from "@/api/ops";
import { getProgrammeDashboard } from "@/api/programme";
import {
  Bar,
  BarChart,
  CartesianGrid,
  Legend,
  Line,
  LineChart,
  ResponsiveContainer,
  Tooltip,
  XAxis,
  YAxis,
} from "recharts";
export const Route = createFileRoute("/p/$pid/dashboard")({ component: Page });
const COLORS = [
  "var(--chart-1)",
  "var(--chart-2)",
  "var(--chart-3)",
  "var(--chart-4)",
  "var(--chart-5)",
];
function Page() {
  const { pid } = Route.useParams();
  const { access } = useAccess();
  const canRecompute = useCan("kpi.recompute");
  const [job, setJob] = useState<string>();
  const q = useQuery({
    queryKey: ["dashboard", "programme"],
    queryFn: () => getProgrammeDashboard(),
    staleTime: 60000,
  });
  const first = access?.userName.split(" ")[0] ?? "";
  return (
    <>
      <PageHeader
        title={`Good ${new Date().getHours() < 12 ? "morning" : "afternoon"}, ${first}`}
        description={`The state of the programme in one screen.${q.data ? ` Data as of ${fmtDateTime(q.data.asOf)}.` : ""}`}
        actions={
          <>
            <ExportMenu
              report="claimed_verified"
              formats={["pdf", "docx", "xlsx", "csv"]}
              label="Claimed and verified"
            />
            <ExportMenu report="executive_pack" formats={["pdf", "docx"]} label="Executive pack" />
            {canRecompute && (
              <Button
                variant="outline"
                onClick={async () => setJob((await startJob("recompute")).jobId)}
              >
                Recompute
              </Button>
            )}
          </>
        }
      />
      {job && (
        <div className="mb-4">
          <JobProgress jobId={job} title="KPI recompute" />
        </div>
      )}
      {q.isPending ? (
        <KpiGridSkeleton n={8} />
      ) : q.isError ? (
        <ErrorState error={q.error} onRetry={() => void q.refetch()} />
      ) : (
        <div className="space-y-6">
          <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-5">
            {q.data.kpis.map((k) => (
              <KpiCard key={k.indicatorCode} k={k} />
            ))}
          </div>
          <Card title="Providers vs their targets" padded={false}>
            <div className="overflow-x-auto">
              <table className="w-full text-[13px] tabular">
                <thead className="bg-surface-2 text-muted-foreground">
                  <tr>
                    <th className="px-4 py-2 text-left">Provider</th>
                    {q.data.matrixCodes.map((c) => (
                      <th key={c} className="px-3 py-2 text-right">
                        {shortIndicator(c)}
                      </th>
                    ))}
                  </tr>
                </thead>
                <tbody>
                  {q.data.matrix.map((r) => (
                    <tr key={r.provider.id} className="border-t">
                      <td className="px-4 py-2">
                        <Link
                          to="/p/$pid/providers/$id"
                          params={{ pid, id: r.provider.id }}
                          className="font-medium hover:text-primary"
                        >
                          {r.provider.name}
                        </Link>
                      </td>
                      {r.cells.map((c) => (
                        <td
                          key={c.code}
                          className={cn(
                            "px-3 py-2 text-right",
                            c.status === "met" && "bg-success-soft text-success",
                            c.status === "not_met" && "bg-danger-soft text-danger",
                            c.status === "no_data" && "text-subtle",
                          )}
                        >
                          {c.unit === "%" ? fmtPct(c.value) : fmtInt(c.value)}
                        </td>
                      ))}
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </Card>
          <div className="grid gap-4 lg:grid-cols-2">
            <Card title="Attendance trend (12 weeks)">
              <div className="h-64">
                <ResponsiveContainer>
                  <LineChart data={q.data.trend}>
                    <CartesianGrid stroke="var(--border)" strokeDasharray="3 3" />
                    <XAxis dataKey="week" fontSize={11} tickFormatter={fmtDate} />
                    <YAxis domain={[60, 100]} fontSize={11} />
                    <Tooltip />
                    <Legend />
                    {q.data.trendSeries.map((s, i) => (
                      <Line
                        key={s}
                        dataKey={s}
                        stroke={COLORS[i % 5]}
                        dot={false}
                        strokeWidth={2}
                      />
                    ))}
                    <Line
                      dataKey="Project"
                      stroke="var(--foreground)"
                      strokeDasharray="5 4"
                      dot={false}
                    />
                  </LineChart>
                </ResponsiveContainer>
              </div>
            </Card>
            <Card title="Trainee funnel">
              <div className="space-y-2.5">
                {q.data.funnel.map((f) => (
                  <div key={f.stage}>
                    <div className="flex justify-between text-[13px]">
                      <span>{f.stage}</span>
                      <span className="font-semibold tabular">{fmtInt(f.value)}</span>
                    </div>
                    <div className="mt-1 h-2.5 rounded bg-surface-2">
                      <div
                        className="h-full rounded bg-primary"
                        style={{ width: `${(f.value / (q.data.funnel[0]?.value || 1)) * 100}%` }}
                      />
                    </div>
                  </div>
                ))}
              </div>
            </Card>
          </div>
          <div className="grid gap-4 lg:grid-cols-3">
            <Card title="Obligations compliance">
              <div className="h-52">
                <ResponsiveContainer>
                  <BarChart data={q.data.obligations}>
                    <XAxis dataKey="code" fontSize={11} />
                    <YAxis fontSize={11} />
                    <Tooltip />
                    <Bar dataKey="approved" stackId="a" fill="var(--success)" />
                    <Bar dataKey="submitted" stackId="a" fill="var(--info)" />
                    <Bar dataKey="open" stackId="a" fill="var(--amber)" />
                    <Bar dataKey="overdue" stackId="a" fill="var(--danger)" />
                  </BarChart>
                </ResponsiveContainer>
              </div>
            </Card>
            <Card
              title="Grievances"
              actions={
                <Link to="/p/$pid/grievances" params={{ pid }} className="text-[13px] text-primary">
                  View all
                </Link>
              }
            >
              <div className="flex items-center gap-4">
                <ProgressRing value={q.data.grievances.slaPct} size={72} label="SLA" />
                <div>
                  <p className="text-2xl font-bold">{q.data.grievances.open}</p>
                  <p className="text-muted-foreground">
                    open cases · SLA {fmtPct(q.data.grievances.slaPct)}
                  </p>
                </div>
              </div>
              <div className="mt-4 grid grid-cols-3 gap-2">
                {q.data.grievances.buckets.map((b) => (
                  <Stat key={b.label} label={b.label} value={b.value} />
                ))}
              </div>
            </Card>
            <Card title="Verification progress">
              <ul className="space-y-3">
                {q.data.runs.map((r) => (
                  <li key={r.id} className="flex items-center gap-3">
                    <ProgressRing value={(r.counts.completed / r.sampleSize) * 100} />
                    <div className="min-w-0 flex-1">
                      <p className="truncate font-medium">{r.indicatorName}</p>
                      <p className="truncate text-[12px] text-muted-foreground">{r.providerName}</p>
                    </div>
                    <StatusBadge status={r.result?.pathway ?? r.status} />
                  </li>
                ))}
              </ul>
            </Card>
          </div>
          <Card title="Data health">
            <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
              {q.data.health.map((h) => (
                <div key={h.code} className="rounded-lg border p-3">
                  <div className="flex items-center justify-between">
                    <span className="font-semibold">{h.name}</span>
                    <span
                      className={cn(
                        "text-lg font-bold",
                        h.score >= 85 ? "text-success" : "text-warning",
                      )}
                    >
                      {h.score}
                    </span>
                  </div>
                  <ul className="mt-1 text-[12px] text-muted-foreground">
                    {h.issues.map((i) => (
                      <li key={i}>• {i}</li>
                    ))}
                  </ul>
                </div>
              ))}
            </div>
          </Card>
        </div>
      )}
    </>
  );
}
