import { createFileRoute, Link } from "@tanstack/react-router";
import { useQuery } from "@tanstack/react-query";
import { Card, DateText, PageHeader, Stat } from "@/components/pbps/page";
import { DetailSkeleton, EmptyState, ErrorState } from "@/components/pbps/states";
import { StatusBadge } from "@/components/pbps/status-badge";
import { NewClassDialog } from "@/components/pbps/class-form";
import { ActionButton } from "@/components/pbps/action";
import { listLocations } from "@/api/admin";
import { addSite, getTraining, removeSite, removeTraining, updateTraining } from "@/api/delivery";
import { Can, useCan } from "@/lib/access";
import { fmtDate, fmtInt, fmtPct } from "@/lib/format";
import { P } from "@/lib/roles";
import { cn } from "@/lib/utils";
import { LEVEL_CLS } from "@/lib/session-nav";

export const Route = createFileRoute("/p/$pid/trainings/$id")({ component: Page });
const WD = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];

function Page() {
  const { pid, id } = Route.useParams();
  const q = useQuery({ queryKey: ["trainings", id], queryFn: () => getTraining(id) });
  const manage = useCan(P.trainingManage);
  const admin = useCan(P.projectManage);
  const nav = Route.useNavigate();
  const loc = useQuery({ queryKey: ["locations"], queryFn: listLocations, enabled: manage });
  if (q.isPending) return <DetailSkeleton />;
  if (q.isError) return <ErrorState error={q.error} onRetry={() => void q.refetch()} />;
  const { training: t, sites, breakdowns } = q.data;
  return (
    <>
      <PageHeader
        title={t.title}
        description={`${t.providerName} · ${t.durationMonths} months · planned ${fmtDate(t.plannedStart)} → ${fmtDate(t.plannedEnd)}`}
        actions={
          <>
            {manage && (
              <>
                <ActionButton
                  size="default"
                  label="Edit"
                  title="Edit training"
                  fields={[
                    { key: "title", label: "Title", required: true },
                    { key: "plannedStart", label: "Planned start", type: "date", required: true },
                    { key: "plannedEnd", label: "Planned end", type: "date", required: true },
                  ]}
                  initial={{
                    title: t.title,
                    plannedStart: t.plannedStart,
                    plannedEnd: t.plannedEnd,
                  }}
                  run={(v) => updateTraining(id, v)}
                  success="Training saved"
                  refresh={["trainings", "providers", "obligations"]}
                />
                <ActionButton
                  size="default"
                  label="Add site"
                  title="Add a delivery site"
                  fields={[
                    {
                      key: "l",
                      label: "Location",
                      type: "select",
                      required: true,
                      options: (loc.data ?? []).map((x): [string, string] => [x.code, x.name]),
                    },
                  ]}
                  run={(v) => addSite(id, v["l"] ?? "")}
                  success="Site added"
                  refresh={["trainings"]}
                  confirmLabel="Add site"
                />
              </>
            )}
            {admin && t.traineesCount === 0 && (
              <ActionButton
                size="default"
                label="Remove"
                title="Remove this empty training?"
                description="Only a training without trainees, attendance and reports can be removed."
                run={() => removeTraining(id)}
                success="Training removed"
                refresh={["trainings"]}
                confirmLabel="Remove"
                destructive
                onDone={() => void nav({ to: "/p/$pid/trainings", params: { pid } })}
              />
            )}
            <span
              className={cn(
                "rounded-full px-2.5 py-1 text-[13px] font-semibold capitalize",
                LEVEL_CLS[t.level],
              )}
            >
              {t.level}
            </span>
          </>
        }
      />
      <div className="mb-6 grid gap-3 sm:grid-cols-4">
        <Stat label="Sites" value={t.sitesCount} />
        <Stat label="Classes" value={`${t.classesCount} (${t.classesOngoing} ongoing)`} />
        <Stat label="Trainees" value={fmtInt(t.traineesCount)} />
        <Stat label="Attendance" value={fmtPct(t.attendanceRate)} />
      </div>
      <div className="grid gap-6 xl:grid-cols-[minmax(0,1fr)_320px]">
        <div className="space-y-4">
          {sites.length === 0 && (
            <EmptyState title="No sites" text="This training has no delivery sites yet." />
          )}
          {sites.map(({ site, classes }) => (
            <Card
              key={site.id}
              title={
                <span>
                  {site.location.name}{" "}
                  <span className="font-normal text-muted-foreground">
                    · {classes.length} classes
                  </span>
                </span>
              }
              actions={
                t.structureOpen && (
                  <Can perm={P.classSchedule}>
                    {classes.length === 0 && manage && (
                      <ActionButton
                        variant="ghost"
                        label="Remove site"
                        title={`Remove ${site.displayName}?`}
                        run={() => removeSite(site.id)}
                        success="Site removed"
                        refresh={["trainings"]}
                        confirmLabel="Remove"
                        destructive
                      />
                    )}
                    <NewClassDialog
                      siteId={site.id}
                      siteLabel={site.displayName}
                      durationMonths={t.durationMonths}
                      defaultWeekdays={[1, 2, 3, 4, 5]}
                    />
                  </Can>
                )
              }
              padded={false}
            >
              {classes.length === 0 ? (
                <EmptyState
                  title="No classes yet"
                  text="Add the first class with its start date, weekdays and shift."
                />
              ) : (
                <div className="overflow-x-auto">
                  <table className="w-full text-[13px] tabular">
                    <thead className="bg-surface-2 text-[12px] text-muted-foreground">
                      <tr>
                        <th className="px-4 py-2 text-left">Class</th>
                        <th className="text-left">Shift</th>
                        <th className="text-left">Weekdays</th>
                        <th className="text-left">Dates</th>
                        <th className="text-left">Status</th>
                        <th className="text-right">Trainees</th>
                        <th className="text-right">Attendance</th>
                        <th className="text-right">Missing</th>
                        <th className="px-4 text-left">Registration</th>
                      </tr>
                    </thead>
                    <tbody>
                      {classes.map((c) => (
                        <tr key={c.id} className="border-t hover:bg-surface-3/60">
                          <td className="px-4 py-2">
                            <Link
                              to="/p/$pid/classes/$id"
                              params={{ pid, id: c.id }}
                              className="font-mono font-medium text-primary hover:underline"
                            >
                              {c.code}
                            </Link>
                            <p className="text-[12px] text-muted-foreground">{c.name}</p>
                          </td>
                          <td className="capitalize">{c.shift?.replace("_", " ") ?? "—"}</td>
                          <td>{c.weekdays.map((d) => WD[d % 7]).join(" ")}</td>
                          <td className="whitespace-nowrap">
                            <DateText value={c.effectiveStart} /> →{" "}
                            <DateText value={c.effectiveEnd} />
                          </td>
                          <td>
                            <StatusBadge status={c.status} />
                          </td>
                          <td className="text-right">{c.trackedTrainees}</td>
                          <td
                            className={cn(
                              "text-right",
                              (c.attendanceRate ?? 100) < 80 && "text-danger",
                            )}
                          >
                            {fmtPct(c.attendanceRate)}
                          </td>
                          <td
                            className={cn(
                              "text-right",
                              c.sessionsMissing > 0 && "font-semibold text-danger",
                            )}
                          >
                            {c.sessionsMissing}
                          </td>
                          <td className="px-4">
                            {!c.registrationOpen ? (
                              <StatusBadge status="closed" label="Closed" />
                            ) : (
                              <StatusBadge status="open" label="Open" />
                            )}
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              )}
            </Card>
          ))}
        </div>
        <Card
          title="Breakdown requests"
          actions={
            <Link to="/p/$pid/breakdowns" params={{ pid }} className="text-[13px] text-primary">
              All
            </Link>
          }
        >
          {breakdowns.length === 0 ? (
            <p className="text-muted-foreground">No breakdowns for this training.</p>
          ) : (
            <ul className="space-y-3">
              {breakdowns.map((b) => (
                <li key={b.id} className="text-[13px]">
                  <div className="flex items-center justify-between gap-2">
                    <span className="font-medium">{b.scopeLabel}</span>
                    <StatusBadge status={b.status === "requested" ? "pending_review" : b.status} />
                  </div>
                  <p className="text-muted-foreground">
                    <DateText value={b.start} /> → <DateText value={b.end} /> · {b.sessionsAffected}{" "}
                    sessions
                  </p>
                </li>
              ))}
            </ul>
          )}
        </Card>
      </div>
    </>
  );
}
