"use client";

import { useQuery } from "@tanstack/react-query";
import { apiFetch } from "@/lib/api-client";
import { useUndoMutation } from "@/hooks/useUndoMutation";

export function ActionHistoryPanel() {
  const { data, isLoading } = useQuery({
    queryKey: ["action-history"],
    queryFn: () =>
      apiFetch<{
        actions: {
          id: string;
          summary: string;
          actionType: string;
          createdAt: string;
          undoable: boolean;
        }[];
      }>("/api/actions/recent"),
  });

  const undo = useUndoMutation({
    onSuccess: () => {
      /* query invalidation handled in hook */
    },
  });

  const actions = data?.actions ?? [];

  return (
    <div className="space-y-4">
      <h2 className="font-bold">Action History</h2>
      <p className="text-xs text-[var(--color-text-muted)]">
        Recent actions you can undo. Actions older than 90 days are automatically pruned.
      </p>

      {isLoading ? (
        <p className="text-sm">Loading...</p>
      ) : actions.length === 0 ? (
        <p className="text-sm text-[var(--color-text-muted)]">No recent actions.</p>
      ) : (
        <ul className="space-y-2">
          {actions.map((a) => (
              <li key={a.id} className="retro-window-inset p-2 flex items-center gap-2 text-sm">
                <div className="flex-1">
                  <p>{a.summary}</p>
                  <p className="text-xs text-[var(--color-text-muted)]">
                    {new Date(a.createdAt).toLocaleString()} · {a.actionType}
                  </p>
                </div>
                {a.undoable && (
                  <button
                    className="retro-btn text-xs"
                    onClick={() => undo.mutate(a.id)}
                    disabled={undo.isPending}
                  >
                    Undo
                  </button>
                )}
              </li>
            )
          )}
        </ul>
      )}
    </div>
  );
}
