'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 { RefreshCw, History } from 'lucide-react';

export default function SuperAdminHistoryPage() {
  const [history, setHistory] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

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

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

  return (
    <div className="space-y-6 p-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-white">History</h1>
          <p className="mt-1 text-sm text-slate-400">Audit trail of all platform rule changes and system events</p>
        </div>
        <button
          onClick={load}
          disabled={loading}
          className="inline-flex items-center gap-2 rounded-lg border border-white/10 bg-white/5 px-4 py-2 text-sm text-slate-300 hover:bg-white/5 disabled:opacity-50"
        >
          <RefreshCw className={`h-4 w-4 ${loading ? 'animate-spin' : ''}`} />
          Refresh
        </button>
      </div>

      {error && (
        <div className="rounded-lg border border-red-500/30 bg-red-500/10 px-4 py-3 text-sm text-red-400">
          {error}
        </div>
      )}

      {loading ? (
        <TableSkeleton rows={8} />
      ) : history.length === 0 ? (
        <div className="rounded-xl border border-white/10 bg-white/5 p-12 text-center text-slate-400">
          <History className="mx-auto mb-3 h-8 w-8 opacity-50" />
          <p>No history records yet. Changes will appear here as rules are modified.</p>
        </div>
      ) : (
        <div className="overflow-x-auto rounded-xl border border-white/10 bg-white/5">
          <table className="w-full text-left text-sm">
            <thead className="border-b border-white/10 text-xs uppercase text-slate-400">
              <tr>
                <th className="px-4 py-3">Action</th>
                <th className="px-4 py-3">Entity</th>
                <th className="px-4 py-3">Entity ID</th>
                <th className="px-4 py-3">Actor</th>
                <th className="px-4 py-3">Timestamp</th>
                <th className="px-4 py-3">Details</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-white/5">
              {history.map((entry: any) => (
                <tr key={entry.id} className="hover:bg-white/[0.02]">
                  <td className="px-4 py-3 text-white">{entry.action}</td>
                  <td className="px-4 py-3 text-slate-300">{entry.entityType}</td>
                  <td className="px-4 py-3 text-slate-300 font-mono text-xs">{entry.entityId}</td>
                  <td className="px-4 py-3 text-slate-300">{entry.actorId}</td>
                  <td className="px-4 py-3 text-slate-400 whitespace-nowrap">{formatDateTime(entry.createdAt)}</td>
                  <td className="px-4 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>
  );
}
