import React, { useState, useEffect } from 'react';
import './AuditLogViewer.css';

interface AuditLog {
  id: string;
  actor: string;
  action: string;
  capabilityId: string;
  beforeState?: string;
  afterState: string;
  timestamp: string;
  reason?: string;
}

const API_BASE = process.env.REACT_APP_API_URL || 'http://localhost:3000';

export const AuditLogViewer: React.FC = () => {
  const [logs, setLogs] = useState<AuditLog[]>([]);
  const [loading, setLoading] = useState(true);
  const [filters, setFilters] = useState({
    capabilityId: '',
    actor: '',
    action: '',
  });

  useEffect(() => {
    fetchLogs();
  }, [filters]);

  const fetchLogs = async () => {
    try {
      const params = new URLSearchParams();
      if (filters.capabilityId) params.append('capabilityId', filters.capabilityId);
      if (filters.actor) params.append('actor', filters.actor);
      if (filters.action) params.append('action', filters.action);

      const response = await fetch(
        `${API_BASE}/api/v1/solacenet/audit/toggles?${params.toString()}`,
        {
          headers: {
            'Authorization': `Bearer ${localStorage.getItem('token')}`,
          },
        }
      );
      const data = await response.json();
      setLogs(data);
    } catch (error) {
      console.error('Failed to fetch audit logs:', error);
    } finally {
      setLoading(false);
    }
  };

  if (loading) {
    return <div className="loading">Loading audit logs...</div>;
  }

  return (
    <div className="audit-log-viewer">
      <h2>Audit Logs</h2>

      <div className="filters">
        <input
          type="text"
          placeholder="Capability ID"
          value={filters.capabilityId}
          onChange={(e) => setFilters({ ...filters, capabilityId: e.target.value })}
        />
        <input
          type="text"
          placeholder="Actor"
          value={filters.actor}
          onChange={(e) => setFilters({ ...filters, actor: e.target.value })}
        />
        <select
          value={filters.action}
          onChange={(e) => setFilters({ ...filters, action: e.target.value })}
        >
          <option value="">All Actions</option>
          <option value="enabled">Enabled</option>
          <option value="disabled">Disabled</option>
          <option value="suspended">Suspended</option>
          <option value="kill_switch">Kill Switch</option>
        </select>
      </div>

      <div className="logs-table">
        <table>
          <thead>
            <tr>
              <th>Timestamp</th>
              <th>Actor</th>
              <th>Action</th>
              <th>Capability</th>
              <th>Before</th>
              <th>After</th>
              <th>Reason</th>
            </tr>
          </thead>
          <tbody>
            {logs.map((log) => (
              <tr key={log.id}>
                <td>{new Date(log.timestamp).toLocaleString()}</td>
                <td>{log.actor}</td>
                <td>
                  <span className={`action-badge action-${log.action}`}>
                    {log.action}
                  </span>
                </td>
                <td>{log.capabilityId}</td>
                <td>{log.beforeState || '-'}</td>
                <td>{log.afterState}</td>
                <td>{log.reason || '-'}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
};
