import { createFileRoute } from "@tanstack/react-router";
import { keepPreviousData, useQuery } from "@tanstack/react-query";
import { Fragment, useState } from "react";
import { Card, PageHeader } from "@/components/pbps/page";
import { DiffView, Select, TextInput } from "@/components/pbps/form";
import { Tbl, useAct, View } from "@/components/pbps/blocks";
import { JobProgress } from "@/components/pbps/job-progress";
import { StatusBadge } from "@/components/pbps/status-badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { exportAuditBundle, listAudit, verifyAudit } from "@/api/admin";
import { Can } from "@/lib/access";
import { fmtDateTime, fmtInt } from "@/lib/format";
import { useDebounce } from "@/lib/hooks";
import { P } from "@/lib/roles";

export const Route = createFileRoute("/p/$pid/admin/audit")({ component: Page });
function Page() {
  const [page, setPage] = useState(1);
  const [f, setF] = useState({ q: "", module: "", actor: "", from: "", to: "" });
  const [open, setOpen] = useState<string>();
  const [job, setJob] = useState<string>();
  const set = (k: keyof typeof f) => (v: string) => {
    setF((s) => ({ ...s, [k]: v }));
    setPage(1);
  };
  const dq = useDebounce(f);
  const q = useQuery({
    queryKey: ["audit", page, dq],
    queryFn: () => listAudit({ page, ...dq }),
    placeholderData: keepPreviousData,
  });
  const ver = useAct((_: void) => verifyAudit(f.from || undefined, f.to || undefined));
  const exp = useAct((_: void) => exportAuditBundle(), { onDone: (r) => setJob(r.jobId) });
  return (
    <>
      <PageHeader
        title="Audit log"
        description="Every change, linked so that tampering is detectable."
        actions={
          <>
            <Can perm={P.auditVerify}>
              <Button variant="outline" disabled={ver.isPending} onClick={() => ver.mutate()}>
                {ver.isPending ? "Checking…" : "Verify integrity"}
              </Button>
            </Can>
            <Can perm={P.auditExport}>
              <Button variant="outline" disabled={exp.isPending} onClick={() => exp.mutate()}>
                Export bundle
              </Button>
            </Can>
          </>
        }
      />
      {ver.data && (
        <p
          role="status"
          className={`mb-4 rounded-lg p-3 text-[13px] ${ver.data.intact ? "bg-success-soft" : "bg-danger-soft text-danger"}`}
        >
          {ver.data.intact
            ? `Chain intact: ${fmtInt(ver.data.checked)} V2 events and ${fmtInt(ver.data.legacyChecked)} V1 events checked.`
            : `Chain broken at ${ver.data.brokenAt}.`}
        </p>
      )}
      {job && (
        <div className="mb-4">
          <JobProgress jobId={job} title="Audit bundle" />
        </div>
      )}
      <div className="mb-4 flex flex-wrap gap-2">
        <TextInput
          className="max-w-56"
          aria-label="Search"
          placeholder="Search"
          value={f.q}
          onChange={set("q")}
        />
        <div className="w-40">
          <Select
            ariaLabel="Module"
            placeholder="Any module"
            value={f.module}
            onChange={set("module")}
            options={[
              "registration",
              "attendance",
              "outcomes",
              "activities",
              "verification",
              "grievance",
              "access",
              "delivery",
            ]}
          />
        </div>
        <TextInput
          className="max-w-44"
          aria-label="Actor"
          placeholder="Actor"
          value={f.actor}
          onChange={set("actor")}
        />
        <Input
          className="w-40"
          type="date"
          aria-label="From"
          value={f.from}
          onChange={(e) => set("from")(e.target.value)}
        />
        <Input
          className="w-40"
          type="date"
          aria-label="To"
          value={f.to}
          onChange={(e) => set("to")(e.target.value)}
        />
      </div>
      <View
        q={q}
        isEmpty={(d) => !d.items.length}
        empty={{ title: "No events", text: "Nothing matches these filters." }}
      >
        {(d) => (
          <Card padded={false}>
            <Tbl head={["When", "Actor", "Action", "Entity", "Summary", ""]}>
              {d.items.map((e) => (
                <Fragment key={e.id}>
                  <tr>
                    <td className="whitespace-nowrap">{fmtDateTime(e.at)}</td>
                    <td>{e.actor}</td>
                    <td className="font-mono text-[12px]">{e.action}</td>
                    <td className="font-mono text-[12px]">{e.entity}</td>
                    <td>
                      {e.summary} {e.legacy && <StatusBadge status="info" label="V1" />}
                    </td>
                    <td>
                      {(e.before || e.after) && (
                        <Button
                          size="sm"
                          variant="ghost"
                          aria-expanded={open === e.id}
                          onClick={() => setOpen(open === e.id ? undefined : e.id)}
                        >
                          Changes
                        </Button>
                      )}
                    </td>
                  </tr>
                  {open === e.id && (
                    <tr>
                      <td colSpan={6}>
                        <DiffView before={e.before} after={e.after} />
                      </td>
                    </tr>
                  )}
                </Fragment>
              ))}
            </Tbl>
            <div className="flex items-center justify-between border-t px-4 py-2 text-[12.5px] text-muted-foreground">
              <span>{fmtInt(d.total)} events</span>
              <span className="flex items-center gap-2">
                <Button
                  size="sm"
                  variant="ghost"
                  disabled={page <= 1}
                  onClick={() => setPage(page - 1)}
                >
                  Previous
                </Button>
                Page {page} of {Math.max(1, Math.ceil(d.total / d.pageSize))}
                <Button
                  size="sm"
                  variant="ghost"
                  disabled={page * d.pageSize >= d.total}
                  onClick={() => setPage(page + 1)}
                >
                  Next
                </Button>
              </span>
            </div>
          </Card>
        )}
      </View>
    </>
  );
}
