import { createFileRoute, Link } from "@tanstack/react-router";
import { ExportMenu } from "@/components/pbps/export-menu";
import { DeleteTrainee } from "@/components/pbps/delete-trainee";
import { useQuery } from "@tanstack/react-query";
import type { ReactNode } from "react";
import {
  Bar,
  BarChart,
  CartesianGrid,
  Legend,
  ResponsiveContainer,
  Tooltip,
  XAxis,
  YAxis,
} from "recharts";
import { Card, DateText, Mono, PageHeader, PhoneText, Stat } from "@/components/pbps/page";
import { Dl, View } from "@/components/pbps/blocks";
import { DetailSkeleton } from "@/components/pbps/states";
import { StatusBadge } from "@/components/pbps/status-badge";
import { Button } from "@/components/ui/button";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { getClass } from "@/api/delivery";
import { listOutcomeStatus } from "@/api/outcomes";
import { getTrainee, getTraineeTimeline } from "@/api/trainees";
import type { Trainee } from "@/api/types";
import { useCan } from "@/lib/access";
import { fmtDate } from "@/lib/dates";
import { fmtDateTime, fmtPct } from "@/lib/format";
import { P } from "@/lib/roles";

export const Route = createFileRoute("/p/$pid/trainees/$id/")({ component: Page });
function Page() {
  const { id } = Route.useParams();
  const q = useQuery({ queryKey: ["trainees", id], queryFn: () => getTrainee(id) });
  return (
    <View q={q} skeleton={<DetailSkeleton />}>
      {(t) => <Detail t={t} />}
    </View>
  );
}
function Detail({ t }: { t: Trainee }) {
  const { pid, id } = Route.useParams();
  const pii = useCan(P.traineePii);
  const upd = useCan(P.traineeUpdate);
  const admin = useCan(P.projectManage);
  const out = useCan(P.outcomeView);
  const remove = useCan(P.traineeDelete);
  const cls = useQuery({ queryKey: ["classes", t.classId], queryFn: () => getClass(t.classId) });
  const hist = useQuery({
    queryKey: ["trainees", id, "timeline"],
    queryFn: () => getTraineeTimeline(id),
  });
  const st = useQuery({
    queryKey: ["outcomes", "status", "one", t.code],
    queryFn: () => listOutcomeStatus({ q: t.code }),
    enabled: out,
  });
  const o = st.data?.items.find((x) => x.traineeId === id);
  const open = !!cls.data?.cls.registrationOpen;
  const live = t.rosterStatus !== "withdrawn";
  return (
    <>
      <PageHeader
        title={t.fullName}
        description={`${t.providerCode} · ${t.trainingTitle} · ${t.siteName}`}
        actions={
          <>
            {pii && (
              <ExportMenu
                report="trainee_profile"
                formats={["pdf", "docx"]}
                label="Profile"
                params={{ traineeId: id }}
                perm="trainee.view"
              />
            )}
            {upd && live && (open || admin) && (
              <Button variant="outline" asChild>
                <Link to="/p/$pid/trainees/$id/edit" params={{ pid, id }}>
                  Edit
                </Link>
              </Button>
            )}
            {remove && <DeleteTrainee pid={pid} id={id} code={t.code} />}
          </>
        }
      >
        <div className="mt-3 flex flex-wrap items-center gap-2">
          <Mono>{t.code}</Mono>
          <StatusBadge status={t.rosterStatus} />
          <StatusBadge status={t.eligibility} />
          {cls.data && !open && (
            <StatusBadge
              status="closed"
              label={cls.data.cls.registrationClosedReason ?? "Registration closed"}
            />
          )}
          {t.systemDropoutRisk && <StatusBadge status="at_risk" />}
        </div>
      </PageHeader>
      <Tabs defaultValue="profile">
        <TabsList className="mb-4">
          <TabsTrigger value="profile">Profile</TabsTrigger>
          <TabsTrigger value="attendance">Attendance</TabsTrigger>
          {out && <TabsTrigger value="outcomes">Outcomes</TabsTrigger>}
          <TabsTrigger value="history">History</TabsTrigger>
        </TabsList>
        <TabsContent value="profile">
          <div className="grid gap-5 lg:grid-cols-2">
            <Card title="Registration">
              <Dl
                items={[
                  ["Trainee ID", <Mono key="i">{t.code}</Mono>],
                  ["Beneficiary ID", t.externalBeneficiaryId ?? "—"],
                  ["Provider", t.providerName ?? t.providerCode],
                  ["Training", t.trainingTitle],
                  ["Site", t.siteName],
                  [
                    "Class",
                    <Link
                      key="c"
                      className="font-mono text-primary hover:underline"
                      to="/p/$pid/classes/$id"
                      params={{ pid, id: t.classId }}
                    >
                      {t.className}
                    </Link>,
                  ],
                  [
                    "Class dates",
                    cls.data
                      ? `${fmtDate(cls.data.cls.effectiveStart)} to ${fmtDate(cls.data.cls.effectiveEnd)}`
                      : "—",
                  ],
                  ["Roster", <StatusBadge key="r" status={t.rosterStatus} />],
                  ["Date on the form", t.formDate ? <DateText key="f" value={t.formDate} /> : "—"],
                  ["Entered in the system", <DateText key="e" value={t.registeredAt} />],
                  ["Entered by", t.registeredBy ?? "—"],
                  ...(t.withdrawnAt
                    ? ([
                        ["Withdrawn", <DateText key="w" value={t.withdrawnAt} />],
                        ["Withdrawal reason", t.withdrawalReason ?? "—"],
                      ] as [string, ReactNode][])
                    : []),
                ]}
              />
            </Card>
            <Card title="Personal">
              <Dl
                items={[
                  ["First name", t.firstName],
                  ["Father's name", t.fatherName],
                  ["Grandfather's name", t.grandfatherName],
                  [
                    "Sex",
                    <span key="s" className="capitalize">
                      {t.sex}
                    </span>,
                  ],
                  ["Age", t.age],
                  [
                    "Date of birth",
                    t.dateOfBirth ? (
                      <DateText key="b" value={t.dateOfBirth} />
                    ) : t.dobRecorded ? (
                      `${t.dobRecorded} (as written in V1)`
                    ) : (
                      "—"
                    ),
                  ],
                ]}
              />
            </Card>
            <Card title="Contact">
              <Dl
                items={[
                  ["Phone", <PhoneText key="p" value={t.phone} masked={!pii} />],
                  ...(pii
                    ? ([
                        [
                          "Alternative phone",
                          t.phoneAlt ? <PhoneText key="a" value={t.phoneAlt} /> : "—",
                        ],
                        ["Email", t.email ?? "—"],
                      ] as [string, ReactNode][])
                    : []),
                  ["Region", t.region],
                  ...(t.subCity ? ([["Sub-city", t.subCity]] as [string, ReactNode][]) : []),
                  ["Woreda", t.woreda],
                  ...(pii
                    ? ([
                        ["Kebele", t.kebele ?? "—"],
                        ["Emergency contact", t.emergencyName ?? "—"],
                        [
                          "Emergency phone",
                          t.emergencyPhone ? <PhoneText key="ep" value={t.emergencyPhone} /> : "—",
                        ],
                      ] as [string, ReactNode][])
                    : []),
                ]}
              />
            </Card>
            <Card title="Education and employment">
              <Dl
                items={[
                  ["Highest education", t.education || "—"],
                  ...(pii
                    ? ([
                        ["Skills training before", yes(t.previouslyParticipated)],
                        ...(t.previouslyParticipated
                          ? ([
                              ["Type of that training", t.priorType ?? "—"],
                              ["Completed it", yes(t.priorCompleted)],
                              ["Year completed", t.priorYear ?? "—"],
                            ] as [string, ReactNode][])
                          : []),
                      ] as [string, ReactNode][])
                    : []),
                  ["Employment (last month)", t.employment || "—"],
                  ...(pii
                    ? ([
                        ["Income sufficient", yes(t.incomeSufficient)],
                        ["Use of skills at work", t.skillUsage ?? "—"],
                        [
                          "Plan after training",
                          [t.plan, t.planOther].filter(Boolean).join(": ") || "—",
                        ],
                      ] as [string, ReactNode][])
                    : []),
                  ["Eligibility", <StatusBadge key="el" status={t.eligibility} />],
                ]}
              />
            </Card>
            {pii && (
              <Card title="Inclusion and consent">
                <Dl
                  items={[
                    ["Inclusion", t.inclusion?.length ? t.inclusion.join(", ") : "—"],
                    ...(t.disability
                      ? ([
                          [
                            "Disability",
                            [t.disability, t.disabilityOther].filter(Boolean).join(": "),
                          ],
                        ] as [string, ReactNode][])
                      : []),
                    ["Information is accurate", yes(t.consentAccuracy)],
                    ["Follow-up surveys", yes(t.consentFollowup)],
                    ["Employment may be verified", yes(t.consentVerify)],
                    ["Use of image", yes(t.consentImage)],
                  ]}
                />
              </Card>
            )}
          </div>
        </TabsContent>
        <TabsContent value="attendance">
          <div className="grid gap-3 sm:grid-cols-3 lg:grid-cols-6">
            <Stat
              label="Rate to date"
              value={fmtPct(t.attendanceRate)}
              tone={(t.attendanceRate ?? 100) < 80 ? "danger" : undefined}
            />
            <Stat label="Highest reachable" value={fmtPct(t.maxReachable)} />
            <Stat label="Sessions" value={`${t.sessionsToDate} / ${t.sessionsTotal}`} />
            <Stat label="Present" value={t.present} />
            {t.excused > 0 && <Stat label="Excused in V1" value={t.excused} />}
            <Stat label="Absent" value={t.absent} />
          </div>
          {!!t.weeks?.length && (
            <Card title="Attendance by week" className="mt-5">
              <div
                className="h-64"
                role="img"
                aria-label={t.weeks
                  .map(
                    (w) => `Week of ${fmtDate(w.week)}: ${w.present} present, ${w.absent} absent`,
                  )
                  .join("; ")}
              >
                <ResponsiveContainer>
                  <BarChart data={t.weeks}>
                    <CartesianGrid vertical={false} stroke="var(--border)" />
                    <XAxis dataKey="week" fontSize={11} tickFormatter={fmtDate} />
                    <YAxis allowDecimals={false} fontSize={11} />
                    <Tooltip labelFormatter={(v) => `Week of ${fmtDate(String(v))}`} />
                    <Legend />
                    <Bar dataKey="present" name="Present" stackId="a" fill="var(--chart-1)" />
                    <Bar dataKey="absent" name="Absent" stackId="a" fill="var(--danger)" />
                    {t.excused > 0 && (
                      <Bar dataKey="excused" name="Excused" stackId="a" fill="var(--chart-3)" />
                    )}
                  </BarChart>
                </ResponsiveContainer>
              </div>
            </Card>
          )}
        </TabsContent>
        <TabsContent value="outcomes">
          <Card>
            <View q={st}>
              {() =>
                o ? (
                  <Dl
                    items={(
                      [
                        ["Dropout", o.dropout],
                        ["Completion", o.completion],
                        ["Certification", o.certification],
                        ["Employment placement", o.placement],
                        ["Locality", o.locality],
                        ["Retention 3 m", o.retention3m],
                      ] as [string, string][]
                    ).map(([l, v]) => [l, <StatusBadge key={l} status={v} />])}
                  />
                ) : (
                  <p>No outcomes: this trainee is withdrawn.</p>
                )
              }
            </View>
          </Card>
        </TabsContent>
        <TabsContent value="history">
          <Card>
            <View
              q={hist}
              empty={{ title: "No events", text: "Changes to this trainee are listed here." }}
            >
              {(d) => (
                <ol className="space-y-3">
                  {d.map((e, i) => (
                    <li key={i}>
                      <p className="font-medium">{e.title}</p>
                      {e.detail && <p className="text-[13px]">{e.detail}</p>}
                      <p className="text-[12px] text-muted-foreground">
                        {e.actor}, {fmtDateTime(e.at)}
                      </p>
                    </li>
                  ))}
                </ol>
              )}
            </View>
          </Card>
        </TabsContent>
      </Tabs>
    </>
  );
}
const yes = (v: boolean | undefined) => (v === undefined ? "—" : v ? "Yes" : "No");
