import { useEffect, useState } from "react";
import { getAuditLog, type AuditLogEntry } from "../../api/adminApi";

export default function AdminActivity() {
  const [entries, setEntries] = useState<AuditLogEntry[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  
  // Filters
  const [actionFilter, setActionFilter] = useState("");
  const [limit, setLimit] = useState(50);

  useEffect(() => {
    loadAuditLog();
  }, [actionFilter, limit]);

  async function loadAuditLog() {
    setLoading(true);
    setError(null);
    try {
      const data = await getAuditLog({
        action: actionFilter || undefined,
        limit,
      });
      setEntries(data.entries);
    } catch (err: any) {
      setError(err.message || "Failed to load audit log");
    } finally {
      setLoading(false);
    }
  }

  function formatAction(action: string): string {
    return action.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
  }

  function getActionColor(action: string): string {
    if (action.includes("delete")) return "bf-action-danger";
    if (action.includes("create")) return "bf-action-success";
    if (action.includes("update")) return "bf-action-warning";
    if (action.includes("login")) return "bf-action-info";
    return "bf-action-default";
  }

  function parseDetails(details: string | null): Record<string, any> | null {
    if (!details) return null;
    try {
      return JSON.parse(details);
    } catch {
      return null;
    }
  }

  const uniqueActions = [...new Set(entries.map((e) => e.action))].sort();

  return (
    <div className="bf-admin-page">
      <div className="bf-admin-header">
        <div>
          <h1>Activity Log</h1>
          <p className="bf-admin-subtitle">Audit trail of system actions</p>
        </div>
        <button className="btn" onClick={loadAuditLog} disabled={loading}>
          Refresh
        </button>
      </div>

      {/* Filters */}
      <div className="bf-admin-filters">
        <select
          value={actionFilter}
          onChange={(e) => setActionFilter(e.target.value)}
          className="bf-admin-filter-select"
        >
          <option value="">All Actions</option>
          {uniqueActions.map((action) => (
            <option key={action} value={action}>{formatAction(action)}</option>
          ))}
        </select>
        
        <select
          value={limit}
          onChange={(e) => setLimit(parseInt(e.target.value))}
          className="bf-admin-filter-select"
        >
          <option value="25">Last 25</option>
          <option value="50">Last 50</option>
          <option value="100">Last 100</option>
          <option value="200">Last 200</option>
        </select>
      </div>

      {error && <div className="bf-admin-error">{error}</div>}

      {loading ? (
        <div className="bf-admin-loading">Loading activity log...</div>
      ) : entries.length > 0 ? (
        <div className="bf-admin-card">
          <div className="bf-admin-activity-list">
            {entries.map((entry) => {
              const details = parseDetails(entry.details);
              
              return (
                <div key={entry.id} className="bf-admin-activity-item">
                  <div className="bf-admin-activity-icon">
                    <span className={`bf-admin-activity-dot ${getActionColor(entry.action)}`} />
                  </div>
                  <div className="bf-admin-activity-content">
                    <div className="bf-admin-activity-header">
                      <span className={`bf-admin-activity-action ${getActionColor(entry.action)}`}>
                        {formatAction(entry.action)}
                      </span>
                      <span className="bf-admin-activity-entity">
                        {entry.entity_type}
                        {entry.entity_id && `: ${entry.entity_id}`}
                      </span>
                    </div>
                    <div className="bf-admin-activity-meta">
                      <span className="bf-admin-activity-user">
                        {entry.username || "System"}
                      </span>
                      <span className="bf-admin-activity-time">
                        {new Date(entry.created_at).toLocaleString()}
                      </span>
                      {entry.ip_address && (
                        <span className="bf-admin-activity-ip">IP: {entry.ip_address}</span>
                      )}
                    </div>
                    {details && Object.keys(details).length > 0 && (
                      <div className="bf-admin-activity-details">
                        {Object.entries(details).map(([key, value]) => (
                          <span key={key} className="bf-admin-activity-detail">
                            <strong>{key}:</strong> {String(value)}
                          </span>
                        ))}
                      </div>
                    )}
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      ) : (
        <div className="bf-admin-empty-state">
          <p>No activity recorded yet</p>
        </div>
      )}
    </div>
  );
}
