import { createFileRoute, Link, useNavigate } from "@tanstack/react-router";
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 { getProviderDashboard } from "@/api/programme";
import { AlertTriangle, CheckCircle2, ChevronRight, Circle } from "lucide-react";
export const Route = createFileRoute("/p/$pid/home")({ component: Page });
const SEV = {
  overdue: "border-l-danger bg-danger-soft/40",
  due_soon: "border-l-amber bg-amber-soft/50",
  open: "border-l-info",
  info: "border-l-border",
};
function Page() {
  const { pid } = Route.useParams();
  const { access } = useAccess();
  const providerId = access?.providerId ?? "";
  const q = useQuery({
    queryKey: ["dashboard", "provider", providerId],
    queryFn: () => getProviderDashboard(providerId),
    staleTime: 60000,
    enabled: !!providerId,
  });
  if (!providerId)
    return (
      <ErrorState
        error={
          new Error(
            "Your account is not linked to a training provider. Contact your administrator.",
          )
        }
      />
    );
  if (q.isPending)
    return (
      <>
        <KpiGridSkeleton />
        <div className="mt-6">
          <TableSkeleton rows={5} />
        </div>
      </>
    );
  if (q.isError) return <ErrorState error={q.error} onRetry={() => void q.refetch()} />;
  const { provider: p, todo, kpis, classes, atRisk, checklist } = q.data;
  return (
    <>
      <PageHeader
        title={p.name}
        description={`Contract target ${fmtInt(p.contractTarget)} trainees`}
      />
      <div className="mb-6 rounded-xl border bg-card p-4">
        <div className="flex justify-between text-[13px]">
          <span>
            Registered {fmtInt(p.registered)} of max {fmtInt(p.maxRegistration)}
          </span>
          <StatusBadge
            status={p.registrationOpen ? "open" : "closed"}
            label={p.registrationOpen ? "Registration open" : "Registration closed"}
          />
        </div>
        <div className="mt-2">
          <TargetBar value={p.registered} target={p.contractTarget} max={p.maxRegistration} />
        </div>
      </div>
      <div className="grid gap-6 lg:grid-cols-[minmax(0,1fr)_320px]">
        <Card title="What needs doing" padded={false}>
          {todo.length === 0 ? (
            <EmptyState title="All caught up" text="Nothing is due right now." />
          ) : (
            <ul>
              {todo.map((t, i) => (
                <li key={i}>
                  <Link
                    to={`/p/$pid/${t.href}` as "/p/$pid/home"}
                    params={{ pid }}
                    className={cn(
                      "flex items-center gap-3 border-b border-l-4 px-4 py-3 hover:bg-surface-2",
                      SEV[t.severity],
                    )}
                  >
                    {t.severity === "overdue" ? (
                      <AlertTriangle className="h-4 w-4 text-danger" />
                    ) : (
                      <Circle className="h-4 w-4 text-muted-foreground" />
                    )}
                    <div className="min-w-0 flex-1">
                      <p className="font-medium">{t.title}</p>
                      {t.detail && <p className="text-[12px] text-muted-foreground">{t.detail}</p>}
                    </div>
                    <StatusBadge status={t.severity} />
                    <ChevronRight className="h-4 w-4 text-subtle" />
                  </Link>
                </li>
              ))}
            </ul>
          )}
        </Card>
        <Card title="Get started">
          {checklist.map((c) => (
            <p key={c.label} className="flex items-center gap-2 py-1.5">
              {c.done ? (
                <CheckCircle2 className="h-4 w-4 text-success" />
              ) : (
                <Circle className="h-4 w-4" />
              )}
              {c.label}
            </p>
          ))}
        </Card>
      </div>
      {kpis.some((k) => k.status !== "no_data") && (
        <>
          <h2 className="mb-3 mt-8 font-display text-lg font-semibold">My results</h2>
          <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
            {kpis
              .filter((k) => k.status !== "no_data")
              .map((k) => (
                <KpiCard key={k.indicatorCode} k={k} />
              ))}
          </div>
        </>
      )}
      <div className="mt-8 grid gap-6 lg:grid-cols-[minmax(0,1fr)_360px]">
        <Card title="Class progress" 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">Class</th>
                  <th className="text-left">Site</th>
                  <th className="text-left">Status</th>
                  <th className="text-right">Trainees</th>
                  <th className="text-right">Attendance</th>
                  <th className="px-4 text-right">Missing</th>
                </tr>
              </thead>
              <tbody>
                {classes.map((c) => (
                  <tr key={c.id} className="border-t hover:bg-surface-2">
                    <td className="px-4 py-2">
                      <Link
                        to="/p/$pid/classes/$id"
                        params={{ pid, id: c.id }}
                        className="font-mono font-medium text-primary"
                      >
                        {c.code}
                      </Link>
                      <p className="text-[12px] text-muted-foreground">{c.trainingTitle}</p>
                    </td>
                    <td>{c.locationName}</td>
                    <td>
                      <StatusBadge status={c.status} />
                    </td>
                    <td className="text-right">{c.trackedTrainees}</td>
                    <td className="text-right">{fmtPct(c.attendanceRate)}</td>
                    <td
                      className={cn(
                        "px-4 text-right",
                        c.sessionsMissing > 0 && "font-semibold text-danger",
                      )}
                    >
                      {c.sessionsMissing}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </Card>
        {atRisk && (
          <Card title="At-risk trainees">
            {atRisk.length === 0 ? (
              <p className="text-muted-foreground">No trainees at risk.</p>
            ) : (
              <ul className="space-y-2">
                {atRisk.map((t) => (
                  <li key={t.id} className="flex justify-between gap-2">
                    <Link
                      to="/p/$pid/trainees/$id"
                      params={{ pid, id: t.id }}
                      className="truncate hover:text-primary"
                    >
                      {t.fullName}
                    </Link>
                    <span className="shrink-0 font-semibold text-danger tabular">
                      {fmtPct(t.maxReachable)}
                    </span>
                  </li>
                ))}
              </ul>
            )}
          </Card>
        )}
      </div>
    </>
  );
}
