import { createFileRoute, Link } from "@tanstack/react-router";
import { useQuery } from "@tanstack/react-query";
import { useState } from "react";
import { Card, DateText, PageHeader } from "@/components/pbps/page";
import { EmptyState, ErrorState, KpiGridSkeleton } from "@/components/pbps/states";
import { Select } from "@/components/pbps/form";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { listTrainings } from "@/api/delivery";
import { listProviderOptions } from "@/api/programme";
import { Can, useAccess } from "@/lib/access";
import { fmtInt, fmtPct } from "@/lib/format";
import { isTpRole, P } from "@/lib/roles";
import { cn } from "@/lib/utils";
import { LEVEL_CLS } from "@/lib/session-nav";

export const Route = createFileRoute("/p/$pid/trainings/")({ component: Page });

function Page() {
  const { pid } = Route.useParams();
  const { access } = useAccess();
  const [q, setQ] = useState("");
  const [level, setLevel] = useState("");
  const [providerId, setProviderId] = useState("");
  const tp = access ? isTpRole(access.roleCode) : false;
  const provs = useQuery({
    queryKey: ["providers", "options"],
    queryFn: listProviderOptions,
    enabled: !tp,
  });
  const list = useQuery({
    queryKey: ["trainings", q, level, providerId],
    queryFn: () =>
      listTrainings({ q, ...(level ? { level } : {}), ...(providerId ? { providerId } : {}) }),
    placeholderData: (p) => p,
  });
  return (
    <>
      <PageHeader
        title="Trainings & classes"
        description="Courses per provider, delivered at sites, taught in classes with their own dates and weekdays."
        actions={
          <Can perm={P.trainingManage}>
            <Button asChild>
              <Link to="/p/$pid/trainings/new" params={{ pid }}>
                New training
              </Link>
            </Button>
          </Can>
        }
      />
      <div className="mb-4 flex flex-wrap gap-2">
        <Input
          className="max-w-xs"
          placeholder="Search title or provider"
          value={q}
          onChange={(e) => setQ(e.target.value)}
        />
        {!tp && (
          <div className="w-56">
            <Select
              ariaLabel="Provider"
              value={providerId}
              onChange={setProviderId}
              placeholder="All providers"
              options={(provs.data ?? []).map((p) => [p.id, `${p.code} · ${p.name}`])}
            />
          </div>
        )}
        <div className="w-44">
          <Select
            ariaLabel="Level"
            value={level}
            onChange={setLevel}
            placeholder="All levels"
            options={[
              ["basic", "Basic"],
              ["intermediate", "Intermediate"],
              ["advanced", "Advanced"],
            ]}
          />
        </div>
        {(q || level || providerId) && (
          <Button
            variant="ghost"
            onClick={() => {
              setQ("");
              setLevel("");
              setProviderId("");
            }}
          >
            Clear all
          </Button>
        )}
      </div>
      {list.isPending ? (
        <KpiGridSkeleton n={6} />
      ) : list.isError ? (
        <ErrorState error={list.error} onRetry={() => void list.refetch()} />
      ) : list.data.items.length === 0 ? (
        <EmptyState
          title={q || level || providerId ? "No results" : "No trainings yet"}
          text={
            q || level || providerId
              ? "Nothing matches these filters."
              : "Add a training to start scheduling classes."
          }
        />
      ) : (
        <div
          className={cn(
            "grid gap-4 md:grid-cols-2 xl:grid-cols-3 transition-opacity",
            list.isFetching && "opacity-70",
          )}
        >
          {list.data.items.map((t) => (
            <Link
              key={t.id}
              to="/p/$pid/trainings/$id"
              params={{ pid, id: t.id }}
              className="block rounded-xl"
            >
              <Card
                title={t.title}
                actions={
                  <span
                    className={cn(
                      "rounded-full px-2 py-0.5 text-[12px] font-semibold capitalize",
                      LEVEL_CLS[t.level],
                    )}
                  >
                    {t.level}
                  </span>
                }
                className="h-full transition-colors hover:border-primary/40"
              >
                <p className="text-muted-foreground">
                  {t.providerName} · {t.durationMonths} months · <DateText value={t.plannedStart} />{" "}
                  → <DateText value={t.plannedEnd} />
                </p>
                <div className="mt-3 grid grid-cols-4 gap-2 text-center">
                  {[
                    ["sites", t.sitesCount],
                    ["classes", t.classesCount],
                    ["trainees", fmtInt(t.traineesCount)],
                    ["attendance", fmtPct(t.attendanceRate)],
                  ].map(([l, v]) => (
                    <div key={l as string}>
                      <p className="text-lg font-bold tabular">{v}</p>
                      <p className="text-[11px] text-muted-foreground">{l}</p>
                    </div>
                  ))}
                </div>
                <div className="mt-3 flex flex-wrap gap-1">
                  {t.locationCodes.map((c) => (
                    <span key={c} className="rounded bg-surface-2 px-1.5 font-mono text-[11px]">
                      {c}
                    </span>
                  ))}
                  <span className="ml-auto text-[12px] text-muted-foreground">
                    {t.classesOngoing} ongoing · {t.classesEnded} ended
                  </span>
                </div>
              </Card>
            </Link>
          ))}
        </div>
      )}
    </>
  );
}
