import { createFileRoute, Link, useNavigate } from "@tanstack/react-router";
import { runDataHealth } from "@/api/ops";
import { useAct } from "@/components/pbps/blocks";
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 { listFindings } from "@/api/ops";
export const Route = createFileRoute("/p/$pid/data-health")({ component: Page });
function Page() {
  const check = useAct((_: void) => runDataHealth(), {
    success: "The check has started. Reload in a minute.",
    refresh: ["data-health", "datahealth"],
  });
  const { pid } = Route.useParams();
  const q = useQuery({ queryKey: ["datahealth"], queryFn: listFindings });
  return (
    <>
      <PageHeader
        title="Data health"
        description="Quality checks per provider, with links to fix each issue."
        actions={
          <Button variant="outline" disabled={check.isPending} onClick={() => check.mutate()}>
            Check now
          </Button>
        }
      />
      {q.isPending ? (
        <TableSkeleton cols={5} />
      ) : q.isError ? (
        <ErrorState error={q.error} />
      ) : (
        <>
          <div className="mb-6 grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
            {q.data.providers.map((p) => (
              <Card key={p.id}>
                <div className="flex items-center gap-3">
                  <ProgressRing value={p.dataHealth} size={60} label="Score" />
                  <div>
                    <p className="font-semibold">{p.name}</p>
                    <p className="text-[12px] text-muted-foreground">score out of 100</p>
                  </div>
                </div>
              </Card>
            ))}
          </div>
          {q.data.findings.length === 0 ? (
            <EmptyState title="No issues" text="All checks pass." />
          ) : (
            <Card padded={false}>
              <table className="w-full text-[13px]">
                <thead className="bg-surface-2 text-muted-foreground">
                  <tr>
                    <th className="px-4 py-2 text-left">Check</th>
                    <th className="text-left">Severity</th>
                    <th className="text-left">Provider</th>
                    <th className="text-left">Details</th>
                    <th className="text-left">First seen</th>
                    <th className="px-4" />
                  </tr>
                </thead>
                <tbody>
                  {q.data.findings.map((f) => (
                    <tr key={f.id} className="border-t">
                      <td className="px-4 py-2 font-medium">{f.check}</td>
                      <td>
                        <StatusBadge
                          status={
                            f.severity === "high"
                              ? "overdue"
                              : f.severity === "medium"
                                ? "due_soon"
                                : "pending"
                          }
                          label={f.severity}
                        />
                      </td>
                      <td>{f.providerCode}</td>
                      <td className="text-muted-foreground">{f.message}</td>
                      <td>
                        <DateText value={f.firstSeen} />
                      </td>
                      <td className="px-4">
                        <Link
                          to={`/p/$pid/${f.href}` as "/p/$pid/home"}
                          params={{ pid }}
                          className="text-primary"
                        >
                          Fix
                        </Link>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </Card>
          )}
        </>
      )}
    </>
  );
}
