import { createFileRoute, Link } from "@tanstack/react-router";
import { useQuery } from "@tanstack/react-query";
import { useState } from "react";
import { Card, DateText, PageHeader, Stat } from "@/components/pbps/page";
import { ConfirmDialog, Field } from "@/components/pbps/form";
import { Tbl, useAct, View } from "@/components/pbps/blocks";
import { CalendarMonth } from "@/components/pbps/calendar-month";
import { DetailSkeleton } from "@/components/pbps/states";
import { StatusBadge } from "@/components/pbps/status-badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { getClass, setActualStart } from "@/api/delivery";
import { reportKey, reportLabel } from "@/api/report-types";
import type { TrainingClass } from "@/api/types";
import { Can, useCan } from "@/lib/access";
import { addDays, diffDays, fmtDate } from "@/lib/dates";
import { fmtDateTime, fmtPct } from "@/lib/format";
import { P } from "@/lib/roles";
import { cn } from "@/lib/utils";

export const Route = createFileRoute("/p/$pid/classes/$id/")({ component: Page });
const WD = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
function Page() {
  const { pid, id } = Route.useParams();
  const q = useQuery({ queryKey: ["classes", id], queryFn: () => getClass(id) });
  const [dlg, setDlg] = useState<"start">();
  const canOut = useCan(P.outcomeSubmit);
  return (
    <View q={q} skeleton={<DetailSkeleton />}>
      {({ cls: c, calendar, roster, outcomes, obligations, snapshots }) => (
        <>
          <PageHeader
            title={`${c.trainingTitle} · ${c.code}`}
            description={`${c.locationName} · ${c.shift?.replace("_", " ") ?? ""} · ${c.weekdays.map((d) => WD[d % 7]).join(" ")} · ${fmtDate(c.effectiveStart)} to ${fmtDate(c.effectiveEnd)} · ${c.registrationOpen ? `registration open until ${fmtDate(c.registrationClosesOn)}` : "registration closed"}`}
            actions={
              <>
                <StatusBadge status={c.status} size="md" />
                {c.status !== "ended" && (
                  <Can perm={P.classSchedule}>
                    <Button variant="outline" onClick={() => setDlg("start")}>
                      Set actual start
                    </Button>
                  </Can>
                )}
                <Can perm={P.attendanceView}>
                  <Button asChild>
                    <Link to="/p/$pid/classes/$id/attendance" params={{ pid, id }}>
                      Attendance sheet
                    </Link>
                  </Button>
                </Can>
              </>
            }
          />
          <div className="mb-5 grid gap-3 sm:grid-cols-4">
            <Stat label="Attendance rate" value={fmtPct(c.attendanceRate)} />
            <Stat label="Sessions to date" value={`${c.sessionsToDate} / ${c.sessionsTotal}`} />
            <Stat
              label="Sessions missing"
              value={c.sessionsMissing}
              tone={c.sessionsMissing ? "danger" : "success"}
            />
            <Stat label="At risk" value={c.atRisk} tone={c.atRisk ? "warning" : undefined} />
          </div>
          <Tabs defaultValue="outcomes">
            <TabsList className="mb-4 h-auto flex-wrap">
              <TabsTrigger value="outcomes">Outcomes</TabsTrigger>
              <TabsTrigger value="schedule">Schedule</TabsTrigger>
              <TabsTrigger value="roster">Roster ({roster.length})</TabsTrigger>
              <TabsTrigger value="activity">Activities</TabsTrigger>
            </TabsList>
            <TabsContent value="outcomes">
              <Card padded={false}>
                <Tbl head={["Report", "Status", "Due", ">Yes", ">No", ""]}>
                  {outcomes.map((o) => (
                    <tr key={reportKey(o.type, o.stageKey)}>
                      <td className="font-medium">{reportLabel(o.type, o.stageKey)}</td>
                      <td>
                        <StatusBadge status={o.state} />
                        {o.reason && (
                          <p className="text-[12px] text-muted-foreground">{o.reason}</p>
                        )}
                      </td>
                      <td>{o.dueDate && <DateText value={o.dueDate} />}</td>
                      <td className="text-right">{o.yes ?? "—"}</td>
                      <td className="text-right">{o.no ?? "—"}</td>
                      <td className="space-x-3 text-right">
                        {o.reportId && (
                          <Link
                            className="text-primary hover:underline"
                            to="/p/$pid/outcome-reports/$id"
                            params={{ pid, id: o.reportId }}
                          >
                            View report
                          </Link>
                        )}
                        {canOut &&
                          ["due", "overdue", "returned", "not_due"].includes(o.state) &&
                          c.status === "ended" && (
                            <Link
                              className="text-primary hover:underline"
                              to="/p/$pid/classes/$id/outcomes/$type"
                              params={{ pid, id, type: o.type }}
                              search={o.stageKey ? { stage: o.stageKey } : {}}
                            >
                              Fill in
                            </Link>
                          )}
                      </td>
                    </tr>
                  ))}
                </Tbl>
              </Card>
            </TabsContent>
            <TabsContent value="schedule">
              <Card>
                <CalendarMonth
                  months={[...new Set(calendar.map((d) => d.date.slice(0, 7)))]}
                  days={calendar}
                />
              </Card>
            </TabsContent>
            <TabsContent value="roster" className="space-y-4">
              <Card padded={false}>
                <Tbl
                  head={[
                    "Trainee",
                    "Sex",
                    ">Age",
                    "Roster",
                    ">Attendance",
                    "Dropout",
                    "Completion",
                  ]}
                >
                  {roster.map((t) => (
                    <tr key={t.id}>
                      <td>
                        <Link
                          to="/p/$pid/trainees/$id"
                          params={{ pid, id: t.id }}
                          className="font-medium hover:text-primary"
                        >
                          {t.fullName}
                        </Link>{" "}
                        <span className="font-mono text-[12px] text-muted-foreground">
                          {t.code}
                        </span>
                      </td>
                      <td className="capitalize">{t.sex}</td>
                      <td className="text-right">{t.age}</td>
                      <td>
                        <StatusBadge status={t.rosterStatus} />
                      </td>
                      <td
                        className={cn(
                          "text-right",
                          (t.attendanceRate ?? 100) < 80 && "text-danger",
                        )}
                      >
                        {fmtPct(t.attendanceRate)}
                      </td>
                      <td>
                        <StatusBadge status={t.dropout} />
                      </td>
                      <td>
                        <StatusBadge status={t.completion} />
                      </td>
                    </tr>
                  ))}
                </Tbl>
              </Card>
              {snapshots.length > 0 && (
                <Card title="Lists kept when registration closed">
                  <ul>
                    {snapshots.map((s) => (
                      <li key={s.id}>
                        {fmtDateTime(s.takenAt)}: {s.members} trainees ({s.kind})
                      </li>
                    ))}
                  </ul>
                </Card>
              )}
            </TabsContent>
            <TabsContent value="activity">
              <Card padded={false}>
                <Tbl head={["Activity", "Due", "Status"]}>
                  {obligations.map((o) => (
                    <tr key={o.id}>
                      <td>
                        <Link
                          className="font-medium hover:text-primary"
                          to="/p/$pid/obligations/$id"
                          params={{ pid, id: o.id }}
                        >
                          {o.activity.name}
                        </Link>
                      </td>
                      <td>
                        <DateText value={o.dueDate} />
                      </td>
                      <td>
                        <StatusBadge status={o.status} />
                      </td>
                    </tr>
                  ))}
                </Tbl>
              </Card>
            </TabsContent>
          </Tabs>
          {dlg === "start" && <StartDialog c={c} onClose={() => setDlg(undefined)} />}
        </>
      )}
    </View>
  );
}
function StartDialog({ c, onClose }: { c: TrainingClass; onClose: () => void }) {
  const [d, setD] = useState(c.actualStart ?? c.plannedStart);
  const m = useAct((_: void) => setActualStart(c.id, d), {
    success: "Actual start saved",
    refresh: ["classes", "trainings", "attendance"],
    onDone: onClose,
  });
  const shift = d ? diffDays(d, c.effectiveStart) : 0;
  return (
    <ConfirmDialog
      open
      onOpenChange={(o) => {
        if (!o) onClose();
      }}
      title="Actual start date"
      description="The end date moves by the same number of days."
      confirmLabel="Save"
      pending={m.isPending || !d}
      onConfirm={() => m.mutate()}
    >
      <Field
        label="Started on"
        required
        help={
          shift
            ? `The class will end on ${fmtDate(addDays(c.effectiveEnd, shift))} instead of ${fmtDate(c.effectiveEnd)}.`
            : "No change to the end date."
        }
      >
        <Input type="date" value={d} onChange={(e) => setD(e.target.value)} />
      </Field>
    </ConfirmDialog>
  );
}
