'use client';

import { useState, useEffect, useCallback } from 'react';
import { businessRulesService } from '@/services/business-rules.service';
import { getErrorMessage } from '@/lib/errors';
import { TableSkeleton } from '@/components/priority/skeletons';
import { formatDateTime } from '@/lib/utils';
import { Banner, useToasts } from './_shared';

export default function HistoryTab() {
  const [history, setHistory] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const { error, setError, Banners } = useToasts();

  const load = useCallback(async () => {
    setLoading(true);
    try { setHistory(await businessRulesService.getRuleHistory()); }
    catch (e: any) { setError(getErrorMessage(e)); }
    finally { setLoading(false); }
  }, [setError]);

  useEffect(() => { load(); }, [load]);

  return (
    <div className="space-y-4">
      <Banners />
      <p className="text-sm text-slate-400">Audit log of every rule change. Read-only.</p>
      {loading ? <TableSkeleton rows={5} /> : history.length === 0 ? <p className="rounded-lg border border-white/10 bg-slate-900/30 p-6 text-center text-sm text-slate-400">No history yet</p> : (
        <div className="overflow-x-auto rounded-xl border border-white/10 bg-slate-900/30">
          <table className="w-full text-sm">
            <thead><tr className="border-b border-white/10 text-left text-slate-400">
              <th className="px-3 py-2">Action</th><th className="px-3 py-2">Entity</th><th className="px-3 py-2">Entity ID</th><th className="px-3 py-2">Actor</th><th className="px-3 py-2">Timestamp</th><th className="px-3 py-2">Details</th>
            </tr></thead>
            <tbody>
              {history.map((entry: any) => (
                <tr key={entry.id} className="border-b border-white/5">
                  <td className="px-3 py-3 text-white">{entry.action}</td>
                  <td className="px-3 py-3 text-slate-300">{entry.entityType}</td>
                  <td className="px-3 py-3 text-slate-300 font-mono text-xs">{entry.entityId}</td>
                  <td className="px-3 py-3 text-slate-300">{entry.actorId}</td>
                  <td className="px-3 py-3 text-slate-300">{formatDateTime(entry.createdAt)}</td>
                  <td className="px-3 py-3 text-slate-300 text-xs max-w-[200px] truncate">{entry.oldValues || entry.newValues ? JSON.stringify({...entry.oldValues, ...entry.newValues}) : '-'}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}
