import { useQuery } from "@tanstack/react-query";
import { Link } from "@tanstack/react-router";
import { History } from "lucide-react";
import { Button } from "@/components/ui/button";
import { AuditDiff } from "@/components/AuditDiff";
import { StatusBadge } from "@/components/ui-kit";
import { formatDateTime } from "@/lib/format";
import { supabase } from "@/integrations/supabase/client";

type LogRow = {
  id: string;
  action: string;
  created_at: string;
  metadata: unknown;
};

/**
 * Shown when the Chart of Accounts is opened from an Audit Log deep link:
 * the linked account's create/edit/delete trail with before/after values.
 */
export function AccountAuditHistory({
  accountId,
  label,
}: {
  accountId: string;
  label: string;
}) {
  const { data: logs = [] } = useQuery({
    queryKey: ["audit_logs", "account", accountId],
    queryFn: async () => {
      const { data, error } = await supabase
        .from("audit_logs")
        .select("id, action, created_at, metadata")
        .eq("entity_type", "account")
        .eq("entity_id", accountId)
        .order("created_at", { ascending: false })
        .limit(10);
      if (error) throw new Error(error.message);
      return (data ?? []) as LogRow[];
    },
  });

  return (
    <div className="rounded-lg border border-primary/30 bg-primary/5 p-4">
      <div className="flex flex-wrap items-center justify-between gap-2">
        <p className="flex items-center gap-2 text-sm font-semibold">
          <History className="size-4 text-primary" aria-hidden />
          Audit trail — {label}
        </p>
        <Button asChild variant="outline" size="sm">
          <Link to="/audit-log">
            Back to audit log
          </Link>
        </Button>
      </div>
      {logs.length === 0 ? (
        <p className="mt-2 text-sm text-muted-foreground">No recorded changes for this account.</p>
      ) : (
        <ul className="mt-3 space-y-3">
          {logs.map((l) => (
            <li key={l.id} className="rounded-md border border-border bg-card p-3">
              <div className="flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
                <StatusBadge status={l.action} />
                <span>{formatDateTime(l.created_at)}</span>
              </div>
              <div className="mt-2">
                <AuditDiff metadata={l.metadata} />
              </div>
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}
