"use client";

import { useQuery } from "@tanstack/react-query";
import { useState } from "react";
import { api } from "@/lib/api";
import { formatDate, formatStamp } from "@/lib/format";
import { Field } from "@/components/Field";
import { PageHeader } from "@/components/PageHeader";

export default function AuditPage() {
    const [filter, setFilter] = useState("");
    const { data } = useQuery({ queryKey: ["staff-audit"], queryFn: () => api.staff.audit() });

    const rows = (data ?? []).filter((e) =>
        filter
            ? `${e.action} ${e.actor} ${e.target ?? ""}`.toLowerCase().includes(filter.toLowerCase())
            : true,
    );

    return (
        <div className="grid gap-6">
            <PageHeader
                title="Audit"
                subtitle="Every mutating action across every account, newest first."
                record={[{ key: "Showing", value: `${rows.length} of ${(data ?? []).length}` }]}
            />
            <Field
                label="Filter"
                value={filter}
                onChange={(e) => setFilter(e.target.value)}
                hint="Action, actor or target."
            />
            <ul className="grid gap-2 rounded border border-rule bg-panel p-5 font-mono text-[0.82rem]">
                {rows.map((e, n) => (
                    <li
                        key={n}
                        className="grid gap-1 border-b border-rule-soft pb-2 last:border-0 sm:grid-cols-[11rem_1fr]"
                    >
                        <span className="tabular-nums text-ink-3">
                            {formatDate(e.created_at)} {formatStamp(e.created_at)}
                        </span>
                        <span className="text-ink-2">
                            <b className="text-ink">{e.action}</b> · {e.actor}
                            {e.target && ` · ${e.target}`}
                            {e.detail && ` · ${e.detail}`}
                        </span>
                    </li>
                ))}
                {rows.length === 0 && <li className="text-ink-3">Nothing matches that.</li>}
            </ul>
        </div>
    );
}
