import { createFileRoute, useNavigate } from "@tanstack/react-router";
import { attendanceExportUrl } from "@/api/delivery";
import { DownloadButton } from "@/components/pbps/blocks";
import { useQuery } from "@tanstack/react-query";
import { useEffect, useRef, useState } from "react";
import { ChevronLeft, ChevronRight, Lock } from "lucide-react";
import { toast } from "sonner";
import { Card, PageHeader } from "@/components/pbps/page";
import {
  ConfirmDialog,
  Field,
  FileDropzone,
  FormError,
  Segmented,
  Select,
  TextArea,
} from "@/components/pbps/form";
import { useAct, View } from "@/components/pbps/blocks";
import { EmptyState, TableSkeleton } from "@/components/pbps/states";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { ApiError } from "@/api/client";
import { attendanceTemplateUrl, importAttendance, requestCorrection } from "@/api/attendance";
import { CalendarMonth } from "@/components/pbps/calendar-month";
import { getAttendanceSheet, submitAttendance, type AttendanceSheet } from "@/api/delivery";
import { newIdempotencyKey } from "@/api/http";
import { useCan } from "@/lib/access";
import { diffDays, fmtDate } from "@/lib/dates";
import { fmtDateTime } from "@/lib/format";
import { P } from "@/lib/roles";
import { cn } from "@/lib/utils";

export const Route = createFileRoute("/p/$pid/classes/$id/attendance/")({
  validateSearch: (s: Record<string, unknown>): { date?: string } =>
    typeof s["date"] === "string" ? { date: s["date"] } : {},
  component: Page,
});
type M = "P" | "A";
/** "E" exists only in old V1 marks. It is shown, and can be corrected, but never chosen. */
type Old = M | "E";
const L: Record<Old, string> = { P: "Present", A: "Absent", E: "Excused in V1" };
function Page() {
  const { id } = Route.useParams();
  const { date } = Route.useSearch();
  const q = useQuery({
    queryKey: ["attendance", id, date ?? ""],
    queryFn: () => getAttendanceSheet(id, date),
  });
  return (
    <View q={q} skeleton={<TableSkeleton rows={12} cols={3} />}>
      {(d) => <Sheet key={`${d.date}-${d.submitted ? 1 : 0}`} d={d} />}
    </View>
  );
}
function Sheet({ d }: { d: AttendanceSheet }) {
  const { pid, id } = Route.useParams();
  const navigate = useNavigate();
  const canSubmit = useCan(P.attendanceSubmit);
  const canCorrect = useCan(P.correctionRequest);
  const cur = d.date;
  const locked = !!d.submitted;
  const draftKey = `pbps.draft.attendance.${id}.${cur}`;
  const [marks, setMarks] = useState<Record<string, Old>>(d.marks);
  const [just, setJust] = useState("");
  const [fix, setFix] = useState<{ id: string; name: string; from: Old }>();
  const idem = useRef(newIdempotencyKey());
  useEffect(() => {
    if (locked) return;
    try {
      const raw = localStorage.getItem(draftKey);
      if (raw) {
        const x = JSON.parse(raw) as { marks: Record<string, Old> };
        setMarks(
          Object.fromEntries(Object.entries(x.marks).filter(([, m]) => m === "P" || m === "A")),
        );
        toast.info("Your unsent marks for this day were restored.");
      }
    } catch {
      /* storage unavailable */
    }
  }, [draftKey, locked]);
  const keep = (m: Record<string, Old>) => {
    setMarks(m);
    try {
      localStorage.setItem(draftKey, JSON.stringify({ marks: m }));
    } catch {
      /* storage unavailable */
    }
  };
  const drop = () => {
    try {
      localStorage.removeItem(draftKey);
    } catch {
      /* storage unavailable */
    }
  };
  const sent = (r: { waiting: boolean }) =>
    r.waiting
      ? `Attendance for ${fmtDate(cur)} was sent to M&E for approval`
      : `Attendance for ${fmtDate(cur)} submitted`;
  const refresh = ["attendance", "classes", "late-requests"];
  const save = useAct(
    (v: Parameters<typeof submitAttendance>[0]) => submitAttendance(v, idem.current),
    { success: sent, refresh, onDone: drop },
  );
  const [files, setFiles] = useState<File[]>([]);
  const up = useAct((f: File) => importAttendance(id, cur ?? "", f, just || undefined), {
    success: sent,
    refresh,
    onError: () => {},
    onDone: () => {
      setFiles([]);
      drop();
    },
  });
  const rows = up.error instanceof ApiError ? up.error.fieldErrors : [];
  const [pick, setPick] = useState<string[]>();
  if (!cur)
    return (
      <>
        <PageHeader title={`Attendance · ${d.cls.code}`} />
        <Card>
          <EmptyState
            title="No sessions yet"
            text="The first session of this class has not taken place."
          />
        </Card>
      </>
    );
  const idx = d.sessionDates.indexOf(cur);
  const go = (dt?: string) => {
    if (dt)
      void navigate({
        to: "/p/$pid/classes/$id/attendance",
        params: { pid, id },
        search: { date: dt },
      });
  };
  const late = diffDays(d.today, cur) > d.lateDays;
  const waiting = d.waiting.includes(cur);
  const count = (m: M) => d.roster.filter((t) => marks[t.id] === m).length;
  const unmarked = d.roster.length - count("P") - count("A");
  const problem = unmarked
    ? `${unmarked} trainees not marked`
    : late && !just.trim()
      ? "Say why it is late"
      : "";
  return (
    <>
      <PageHeader
        title={`Attendance · ${d.cls.code}`}
        description={`${d.cls.trainingTitle} · ${d.cls.locationName}`}
        actions={
          <>
            <DownloadButton size="default" path={attendanceExportUrl(id, "xlsx")}>
              Export all days
            </DownloadButton>
            <Button variant="outline" onClick={() => setPick(pick ? undefined : [])}>
              {pick ? "Close" : "Export some days"}
            </Button>
          </>
        }
      />
      {pick && (
        <Card title="Choose the days to export" className="mb-4">
          <div className="flex flex-wrap gap-2">
            {d.sessionDates
              .filter((x) => !d.missing.includes(x))
              .map((x) => (
                <Button
                  key={x}
                  size="sm"
                  variant={pick.includes(x) ? "default" : "outline"}
                  aria-pressed={pick.includes(x)}
                  onClick={() =>
                    setPick(pick.includes(x) ? pick.filter((y) => y !== x) : [...pick, x])
                  }
                >
                  {fmtDate(x)}
                </Button>
              ))}
          </div>
          {pick.length > 0 && (
            <div className="mt-3 flex gap-2">
              <DownloadButton path={attendanceExportUrl(id, "xlsx", pick)}>
                Excel ({pick.length} days)
              </DownloadButton>
              <DownloadButton path={attendanceExportUrl(id, "csv", pick)}>CSV</DownloadButton>
            </div>
          )}
        </Card>
      )}
      <div className="grid items-start gap-5 xl:grid-cols-[minmax(0,1fr)_330px]">
        <div className="xl:order-2 xl:sticky xl:top-20">
          <DayPicker d={d} cur={cur} go={go} />
        </div>
        <div className="min-w-0">
          <div className="mb-4 flex flex-wrap items-center gap-2">
            <Button
              variant="outline"
              size="icon"
              disabled={idx <= 0}
              onClick={() => go(d.sessionDates[idx - 1])}
              aria-label="Previous session"
            >
              <ChevronLeft />
            </Button>
            <div className="w-52">
              <Select
                ariaLabel="Session date"
                value={cur}
                onChange={go}
                options={[...d.sessionDates]
                  .reverse()
                  .map((x) => [
                    x,
                    `${fmtDate(x)}${d.waiting.includes(x) ? " · waiting" : d.missing.includes(x) ? " · missing" : ""}`,
                  ])}
              />
            </div>
            <Button
              variant="outline"
              size="icon"
              disabled={idx >= d.sessionDates.length - 1}
              onClick={() => go(d.sessionDates[idx + 1])}
              aria-label="Next session"
            >
              <ChevronRight />
            </Button>
            {d.missing.length > 0 && (
              <span className="text-[13px] text-danger">
                {d.missing.length} session days are missing. No report can be submitted until they
                are recorded.
              </span>
            )}
          </div>
          {d.requestedDate && d.requestedDate !== cur && (
            <p role="status" className="mb-3 rounded-lg bg-warning-soft p-3 text-[13px]">
              {d.notSession ?? `${fmtDate(d.requestedDate)} is not a session day of this class.`}{" "}
              {fmtDate(cur)} is shown.
            </p>
          )}
          {locked ? (
            <p className="mb-3 flex items-center gap-2 rounded-lg bg-surface-2 px-3 py-2 text-[13px]">
              <Lock className="h-4 w-4 shrink-0" />
              Submitted by {d.submitted?.by}, {d.submitted && fmtDateTime(d.submitted.at)}. Marks
              change only through a correction.
            </p>
          ) : (
            <div className="mb-3 flex flex-wrap items-center gap-3">
              {canSubmit && (
                <Button
                  variant="outline"
                  onClick={() => keep(Object.fromEntries(d.roster.map((t) => [t.id, "P" as M])))}
                >
                  Mark all present
                </Button>
              )}
              <span className="text-[13px] tabular" aria-live="polite">
                Present {count("P")} · Absent {count("A")} · Not marked {unmarked}
              </span>
            </div>
          )}
          {waiting && (
            <p role="status" className="mb-3 rounded-lg bg-info-soft p-3 text-[13px]">
              This day was sent late and is waiting for M&amp;E approval.
            </p>
          )}
          {late && !locked && !waiting && d.lateApproval && canSubmit && (
            <p className="mb-3 rounded-lg bg-info-soft p-3 text-[13px]">
              Attendance this late is recorded only after M&amp;E approves it.
            </p>
          )}
          {late && !locked && !waiting && canSubmit && (
            <div className="mb-3 rounded-lg border border-warning/40 bg-warning-soft p-3">
              <Field
                label={`This date is more than ${d.lateDays} days old. Why is it late?`}
                required
              >
                <Input className="bg-card" value={just} onChange={(e) => setJust(e.target.value)} />
              </Field>
            </div>
          )}
          <Card padded={false}>
            <ul>
              {d.roster.map((t) => {
                const m = marks[t.id];
                return (
                  <li
                    key={t.id}
                    className="flex flex-wrap items-center gap-3 border-b px-4 py-2.5 last:border-0"
                  >
                    <div className="min-w-40 flex-1">
                      <p className="truncate font-medium">{t.fullName}</p>
                      <p className="font-mono text-[12px] text-muted-foreground">
                        {t.code}
                        {t.rosterStatus === "reserve" && " · reserve"}
                      </p>
                    </div>
                    {m === "E" && <span className="text-[12px] text-warning">{L.E}</span>}
                    <div
                      className="flex overflow-hidden rounded-md border"
                      role="radiogroup"
                      aria-label={`Attendance for ${t.fullName}`}
                    >
                      {(["P", "A"] as M[]).map((x) => (
                        <button
                          key={x}
                          type="button"
                          role="radio"
                          aria-checked={m === x}
                          disabled={locked || waiting || !canSubmit}
                          onClick={() => keep({ ...marks, [t.id]: x })}
                          className={cn(
                            "h-11 w-20 border-l text-[13px] font-medium first:border-l-0 disabled:cursor-default",
                            m === x
                              ? x === "P"
                                ? "bg-success text-primary-foreground"
                                : "bg-danger text-primary-foreground"
                              : "bg-card",
                            !locked && m !== x && "hover:bg-surface-2",
                          )}
                        >
                          {L[x]}
                        </button>
                      ))}
                    </div>
                    {locked && canCorrect && m && (
                      <Button
                        size="sm"
                        variant="ghost"
                        onClick={() => setFix({ id: t.id, name: t.fullName, from: m })}
                      >
                        Request correction
                      </Button>
                    )}
                  </li>
                );
              })}
            </ul>
          </Card>
          {!locked && !waiting && canSubmit && (
            <Card title={`Or use a file for ${fmtDate(cur)}`} className="mt-4">
              <FormError error={up.error} />
              {rows.length > 0 && (
                <ul className="mb-3 max-h-56 overflow-y-auto text-[13px]">
                  {rows.map((x) => (
                    <li key={x.path + x.message}>
                      <b>{x.path}</b>: {x.message}
                    </li>
                  ))}
                </ul>
              )}
              <p className="mb-3 text-[13px] text-muted-foreground">
                The template holds this day only. Write present or absent for every trainee, then
                upload it.
              </p>
              <div className="mb-3 flex flex-wrap gap-2">
                <DownloadButton path={attendanceTemplateUrl(id, cur, "csv")}>
                  Template (CSV)
                </DownloadButton>
                <DownloadButton path={attendanceTemplateUrl(id, cur, "xlsx")}>
                  Template (Excel)
                </DownloadButton>
              </div>
              <FileDropzone
                accept={["csv", "xlsx"]}
                maxSizeMb={10}
                files={files}
                onFiles={setFiles}
              />
              <div className="mt-3 flex justify-end">
                <Button
                  disabled={!files[0] || up.isPending || (late && !just.trim())}
                  onClick={() => files[0] && up.mutate(files[0])}
                >
                  {up.isPending ? "Uploading…" : `Upload ${fmtDate(cur)}`}
                </Button>
              </div>
            </Card>
          )}
          {!locked && !waiting && canSubmit && (
            <div className="sticky bottom-0 z-10 mt-4 flex flex-wrap items-center justify-end gap-3 border-t bg-background py-3">
              <span className="text-[13px] text-muted-foreground">{problem}</span>
              <Button
                size="lg"
                disabled={!!problem || save.isPending}
                onClick={() =>
                  save.mutate({
                    classId: id,
                    date: cur,
                    marks: marks as Record<string, M>,
                    ...(just ? { justification: just } : {}),
                  })
                }
              >
                {save.isPending ? "Submitting…" : `Submit attendance for ${fmtDate(cur)}`}
              </Button>
            </div>
          )}
        </div>
      </div>
      {fix && (
        <CorrectionDialog
          classId={id}
          date={cur}
          {...fix}
          traineeId={fix.id}
          onClose={() => setFix(undefined)}
        />
      )}
    </>
  );
}
/** The month with its sessions, holidays and breakdowns. Only session days up to today can be opened. */
function DayPicker({ d, cur, go }: { d: AttendanceSheet; cur: string; go: (x: string) => void }) {
  const months = [...new Set(d.calendar.map((x) => x.date.slice(0, 7)))];
  const [ym, setYm] = useState(cur.slice(0, 7));
  const i = Math.max(0, months.indexOf(ym));
  const named = d.calendar.filter((x) => x.date.startsWith(months[i] ?? "") && x.label);
  return (
    <Card
      title="Session days"
      actions={
        <span className="flex gap-1">
          <Button
            size="sm"
            variant="outline"
            aria-label="Earlier month"
            disabled={i === 0}
            onClick={() => setYm(months[i - 1]!)}
          >
            <ChevronLeft />
          </Button>
          <Button
            size="sm"
            variant="outline"
            aria-label="Later month"
            disabled={i >= months.length - 1}
            onClick={() => setYm(months[i + 1]!)}
          >
            <ChevronRight />
          </Button>
        </span>
      }
    >
      <div>
        <CalendarMonth
          months={[months[i] ?? ym]}
          days={d.calendar}
          selected={cur}
          onSelect={(x) => {
            if (x <= d.today) go(x);
          }}
        />
      </div>
      {named.length > 0 && (
        <ul className="mt-3 space-y-1 text-[12.5px]">
          {named.map((x) => (
            <li key={x.date}>
              <b>{fmtDate(x.date)}</b>: {x.label} ({x.kind})
            </li>
          ))}
        </ul>
      )}
    </Card>
  );
}
function CorrectionDialog({
  classId,
  date,
  traineeId,
  name,
  from,
  onClose,
}: {
  classId: string;
  date: string;
  traineeId: string;
  name: string;
  from: Old;
  onClose: () => void;
}) {
  const [to, setTo] = useState<M>();
  const [reason, setReason] = useState("");
  const [err, setErr] = useState("");
  const m = useAct((v: M) => requestCorrection({ classId, date, traineeId, to: v, reason }), {
    success: "Correction sent to M&E",
    refresh: ["corrections"],
    onDone: onClose,
  });
  return (
    <ConfirmDialog
      open
      onOpenChange={(o) => {
        if (!o) onClose();
      }}
      title={`Correct ${name}, ${fmtDate(date)}`}
      description={`Currently ${L[from]}.`}
      confirmLabel="Send request"
      pending={m.isPending}
      onConfirm={() => {
        if (!to) setErr("Choose the correct mark.");
        else if (reason.trim().length < 5) setErr("Write a reason (at least 5 characters).");
        else m.mutate(to);
      }}
    >
      <div className="space-y-3">
        {err && (
          <p role="alert" className="text-[13px] text-danger">
            {err}
          </p>
        )}
        <Field label="Correct mark" required>
          <Segmented
            value={to}
            onChange={setTo}
            options={(["P", "A"] as M[])
              .filter((x) => x !== from)
              .map((x): [M, string] => [x, L[x]])}
          />
        </Field>
        <Field label="Reason" required>
          <TextArea value={reason} onChange={setReason} maxLength={500} />
        </Field>
      </div>
    </ConfirmDialog>
  );
}
