import { useState, useEffect } from 'react'
import { useAuth } from '../contexts/AuthContext'

const AuditLogs = () => {
  const { authFetch } = useAuth()
  const [logs, setLogs] = useState([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')
  const [filters, setFilters] = useState({
    action: '',
    resourceType: '',
    userId: '',
  })
  const [pagination, setPagination] = useState({
    limit: 100,
    offset: 0,
    total: 0,
    hasMore: false,
  })
  const [expandedLogs, setExpandedLogs] = useState(new Set())

  const fetchLogs = async (silent = false) => {
    try {
      if (!silent) {
        setLoading(true)
      }
      setError('')

      const params = new URLSearchParams({
        limit: pagination.limit.toString(),
        offset: pagination.offset.toString(),
      })

      if (filters.action) params.append('action', filters.action)
      if (filters.resourceType) params.append('resourceType', filters.resourceType)
      if (filters.userId) params.append('userId', filters.userId)

      const response = await authFetch(`/api/audit-logs?${params.toString()}`)
      if (!response.ok) {
        throw new Error('Fehler beim Laden der Audit-Logs')
      }

      const data = await response.json()
      console.log('Audit-Logs Response:', data)
      console.log('Anzahl Logs:', data.logs?.length || 0)
      setLogs(data.logs || [])
      setPagination({
        ...pagination,
        total: data.total || 0,
        hasMore: data.hasMore || false,
      })
    } catch (err) {
      console.error('Error fetching audit logs:', err)
      if (!silent) {
        setError('Fehler beim Laden der Audit-Logs')
      }
    } finally {
      if (!silent) {
        setLoading(false)
      }
    }
  }

  useEffect(() => {
    fetchLogs()
  }, [filters.action, filters.resourceType, filters.userId, pagination.offset])

  // Automatische Aktualisierung alle 5 Sekunden (silent, ohne Loading-State)
  useEffect(() => {
    const interval = setInterval(() => {
      fetchLogs(true) // Silent update - kein Loading-State
    }, 5000) // Aktualisiere alle 5 Sekunden

    return () => clearInterval(interval)
  }, [filters.action, filters.resourceType, filters.userId, pagination.offset])

  const handleFilterChange = (key, value) => {
    setFilters({ ...filters, [key]: value })
    setPagination({ ...pagination, offset: 0 })
  }

  const handlePreviousPage = () => {
    if (pagination.offset > 0) {
      setPagination({
        ...pagination,
        offset: Math.max(0, pagination.offset - pagination.limit),
      })
    }
  }

  const handleNextPage = () => {
    if (pagination.hasMore) {
      setPagination({
        ...pagination,
        offset: pagination.offset + pagination.limit,
      })
    }
  }

  const formatTimestamp = (timestamp) => {
    try {
      if (!timestamp) {
        return { date: '-', time: '-' }
      }

      // Handle ISO format (2025-11-20T16:45:22Z)
      if (timestamp.match(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/)) {
        const [datePart, timePart] = timestamp.split('T')
        const timeOnly = timePart.split(/[Z+-]/)[0] // Entferne Zeitzone-Info (Z, +, -)
        
        return {
          date: datePart, // 2025-11-20
          time: timeOnly   // 16:45:22
        }
      }
      
      // Handle SQLite DATETIME format (YYYY-MM-DD HH:MM:SS)
      if (timestamp.match(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/)) {
        const [datePart, timePart] = timestamp.split(' ')
        
        return {
          date: datePart, // 2025-11-20
          time: timePart  // 16:45:22
        }
      }
      
      // Fallback für andere Formate
      return { date: timestamp, time: '-' }
    } catch (error) {
      // Fallback: Zeige den Timestamp direkt an
      console.error('Fehler beim Formatieren des Timestamps:', error, timestamp)
      return { date: timestamp || '-', time: '-' }
    }
  }

  const getActionColor = (action) => {
    const colors = {
      CREATE: 'text-green-400',
      UPDATE: 'text-blue-400',
      DELETE: 'text-red-400',
      UPLOAD: 'text-yellow-400',
      SIGN: 'text-purple-400',
      ENABLE: 'text-green-400',
      DISABLE: 'text-orange-400',
    }
    return colors[action] || 'text-slate-300'
  }

  const actionLabels = {
    CREATE: 'Erstellt',
    UPDATE: 'Aktualisiert',
    DELETE: 'Gelöscht',
    UPLOAD: 'Hochgeladen',
    SIGN: 'Signiert',
    ENABLE: 'Aktiviert',
    DISABLE: 'Deaktiviert',
  }

  const resourceTypeLabels = {
    user: 'Benutzer',
    space: 'Space',
    fqdn: 'FQDN',
    csr: 'CSR',
    provider: 'Provider',
    certificate: 'Zertifikat',
    permission_group: 'Berechtigungsgruppen',
  }

  const toggleLogExpansion = (logId) => {
    setExpandedLogs(prev => {
      const newSet = new Set(prev)
      if (newSet.has(logId)) {
        newSet.delete(logId)
      } else {
        newSet.add(logId)
      }
      return newSet
    })
  }

  const formatDetails = (details) => {
    if (!details) return '-'
    try {
      const parsed = typeof details === 'string' ? JSON.parse(details) : details
      return JSON.stringify(parsed, null, 2)
    } catch {
      return details
    }
  }

  return (
    <div className="min-h-screen bg-gradient-to-r from-slate-700 to-slate-900 p-6">
      <div className="max-w-7xl mx-auto">
        <div className="mb-6 flex items-center justify-between">
          <div>
            <h1 className="text-3xl font-bold text-white mb-2">Audit Log</h1>
            <p className="text-slate-300">Übersicht aller Systemaktivitäten und Änderungen</p>
          </div>
          <div className="flex items-center gap-2 text-sm text-slate-400">
            <div className="w-2 h-2 bg-green-500 rounded-full animate-pulse"></div>
            <span>Live-Aktualisierung aktiv</span>
          </div>
        </div>

        {/* Filter */}
        <div className="bg-slate-800/50 border border-slate-600/50 rounded-lg p-4 mb-6">
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div>
              <label className="block text-sm font-medium text-slate-200 mb-2">
                Aktion
              </label>
              <select
                value={filters.action}
                onChange={(e) => handleFilterChange('action', e.target.value)}
                className="w-full px-4 py-2 bg-slate-700/50 border border-slate-600 rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-blue-500"
              >
                <option value="">Alle Aktionen</option>
                <option value="CREATE">Erstellt</option>
                <option value="UPDATE">Aktualisiert</option>
                <option value="DELETE">Gelöscht</option>
                <option value="UPLOAD">Hochgeladen</option>
                <option value="SIGN">Signiert</option>
                <option value="ENABLE">Aktiviert</option>
                <option value="DISABLE">Deaktiviert</option>
              </select>
            </div>
            <div>
              <label className="block text-sm font-medium text-slate-200 mb-2">
                Ressourcentyp
              </label>
              <select
                value={filters.resourceType}
                onChange={(e) => handleFilterChange('resourceType', e.target.value)}
                className="w-full px-4 py-2 bg-slate-700/50 border border-slate-600 rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-blue-500"
              >
                <option value="">Alle Typen</option>
                <option value="user">Benutzer</option>
                <option value="space">Space</option>
                <option value="fqdn">FQDN</option>
                <option value="csr">CSR</option>
                <option value="provider">Provider</option>
                <option value="certificate">Zertifikat</option>
                <option value="permission_group">Berechtigungsgruppen</option>
              </select>
            </div>
            <div>
              <label className="block text-sm font-medium text-slate-200 mb-2">
                Benutzer-ID
              </label>
              <input
                type="text"
                value={filters.userId}
                onChange={(e) => handleFilterChange('userId', e.target.value)}
                placeholder="Benutzer-ID filtern"
                className="w-full px-4 py-2 bg-slate-700/50 border border-slate-600 rounded-lg text-white placeholder-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-500"
              />
            </div>
          </div>
        </div>

        {/* Logs Table */}
        {error && (
          <div className="bg-red-500/20 border border-red-500/50 rounded-lg p-4 mb-6 text-red-200">
            {error}
          </div>
        )}

        {loading ? (
          <div className="bg-slate-800/50 border border-slate-600/50 rounded-lg p-8 text-center">
            <svg className="animate-spin h-12 w-12 text-blue-500 mx-auto mb-4" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
              <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
              <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
            </svg>
            <p className="text-slate-300">Lade Audit-Logs...</p>
          </div>
        ) : logs.length === 0 ? (
          <div className="bg-slate-800/50 border border-slate-600/50 rounded-lg p-8 text-center">
            <p className="text-slate-300">Keine Audit-Logs gefunden</p>
          </div>
        ) : (
          <>
            <div className="bg-slate-800/50 border border-slate-600/50 rounded-lg overflow-hidden">
              <div className="overflow-x-auto">
                <table className="w-full">
                  <thead className="bg-slate-700/50">
                    <tr>
                      <th className="px-4 py-3 text-left text-xs font-medium text-slate-300 uppercase tracking-wider w-12">
                      </th>
                      <th className="px-4 py-3 text-left text-xs font-medium text-slate-300 uppercase tracking-wider">
                        Zeitstempel
                      </th>
                      <th className="px-4 py-3 text-left text-xs font-medium text-slate-300 uppercase tracking-wider">
                        Benutzer
                      </th>
                      <th className="px-4 py-3 text-left text-xs font-medium text-slate-300 uppercase tracking-wider">
                        Aktion
                      </th>
                      <th className="px-4 py-3 text-left text-xs font-medium text-slate-300 uppercase tracking-wider">
                        Ressource
                      </th>
                      <th className="px-4 py-3 text-left text-xs font-medium text-slate-300 uppercase tracking-wider">
                        Details
                      </th>
                      <th className="px-4 py-3 text-left text-xs font-medium text-slate-300 uppercase tracking-wider">
                        IP-Adresse
                      </th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-slate-700/50">
                    {logs.map((log) => {
                      const isExpanded = expandedLogs.has(log.id)
                      return (
                        <>
                          <tr key={log.id} className="hover:bg-slate-700/30 transition-colors cursor-pointer" onClick={() => toggleLogExpansion(log.id)}>
                            <td className="px-4 py-3 text-sm text-slate-400">
                              <svg
                                className={`w-4 h-4 transition-transform ${isExpanded ? 'rotate-90' : ''}`}
                                fill="none"
                                stroke="currentColor"
                                viewBox="0 0 24 24"
                              >
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
                              </svg>
                            </td>
                            <td className="px-4 py-3 text-sm text-slate-300">
                              <span className="font-mono text-xs">
                                {formatTimestamp(log.timestamp).date} // {formatTimestamp(log.timestamp).time || '-'}
                              </span>
                            </td>
                            <td className="px-4 py-3 text-sm text-slate-300">
                              {log.username || log.userId || '-'}
                            </td>
                            <td className="px-4 py-3 text-sm">
                              <span className={`font-semibold ${getActionColor(log.action)}`}>
                                {actionLabels[log.action] || log.action}
                              </span>
                            </td>
                            <td className="px-4 py-3 text-sm text-slate-300">
                              <div>
                                <span className="text-slate-400">
                                  {resourceTypeLabels[log.resourceType] || log.resourceType}
                                </span>
                                {log.resourceId && (
                                  <span className="ml-2 text-xs text-slate-500">
                                    ({log.resourceId.substring(0, 8)}...)
                                  </span>
                                )}
                              </div>
                            </td>
                            <td className="px-4 py-3 text-sm text-slate-300 max-w-md truncate">
                              {log.details ? (
                                <span className="truncate block">
                                  {typeof log.details === 'string' && log.details.length > 50
                                    ? log.details.substring(0, 50) + '...'
                                    : log.details}
                                </span>
                              ) : (
                                '-'
                              )}
                            </td>
                            <td className="px-4 py-3 text-sm text-slate-400">
                              {log.ipAddress || '-'}
                            </td>
                          </tr>
                          {isExpanded && (
                            <tr key={`${log.id}-details`} className="bg-slate-800/50">
                              <td colSpan="7" className="px-4 py-4">
                                <div className="space-y-3">
                                  <div>
                                    <h4 className="text-xs font-semibold text-slate-400 uppercase mb-2">Vollständige Details</h4>
                                    <pre className="bg-slate-900/50 border border-slate-700/50 rounded-lg p-4 text-xs text-slate-300 overflow-x-auto">
                                      {formatDetails(log.details)}
                                    </pre>
                                  </div>
                                  {log.userAgent && (
                                    <div>
                                      <h4 className="text-xs font-semibold text-slate-400 uppercase mb-1">User-Agent</h4>
                                      <p className="text-xs text-slate-300 break-all">{log.userAgent}</p>
                                    </div>
                                  )}
                                  {log.resourceId && (
                                    <div>
                                      <h4 className="text-xs font-semibold text-slate-400 uppercase mb-1">Ressourcen-ID</h4>
                                      <p className="text-xs text-slate-300 font-mono">{log.resourceId}</p>
                                    </div>
                                  )}
                                  {log.userId && (
                                    <div>
                                      <h4 className="text-xs font-semibold text-slate-400 uppercase mb-1">Benutzer-ID</h4>
                                      <p className="text-xs text-slate-300 font-mono">{log.userId}</p>
                                    </div>
                                  )}
                                </div>
                              </td>
                            </tr>
                          )}
                        </>
                      )
                    })}
                  </tbody>
                </table>
              </div>
            </div>

            {/* Pagination */}
            <div className="mt-4 flex items-center justify-between">
              <div className="text-sm text-slate-300">
                Zeige {pagination.offset + 1} - {Math.min(pagination.offset + pagination.limit, pagination.total)} von {pagination.total} Einträgen
              </div>
              <div className="flex gap-2">
                <button
                  onClick={handlePreviousPage}
                  disabled={pagination.offset === 0}
                  className="px-4 py-2 bg-slate-700/50 border border-slate-600 rounded-lg text-white disabled:opacity-50 disabled:cursor-not-allowed hover:bg-slate-700 transition-colors"
                >
                  Zurück
                </button>
                <button
                  onClick={handleNextPage}
                  disabled={!pagination.hasMore}
                  className="px-4 py-2 bg-slate-700/50 border border-slate-600 rounded-lg text-white disabled:opacity-50 disabled:cursor-not-allowed hover:bg-slate-700 transition-colors"
                >
                  Weiter
                </button>
              </div>
            </div>
          </>
        )}
      </div>
    </div>
  )
}

export default AuditLogs

