'use client'

import { useState, useEffect } from 'react'
import { Search, Filter, Calendar, User, Activity, Eye, Download } from 'lucide-react'
import LoadingSpinner from '@/components/LoadingSpinner'

interface AuditLog {
  id: string
  user: string
  action: string
  entity: string
  entityId: string
  changes?: any
  ipAddress: string
  timestamp: string
}

export default function AuditLogsPage() {
  const [logs, setLogs] = useState<AuditLog[]>([])
  const [loading, setLoading] = useState(true)
  const [searchTerm, setSearchTerm] = useState('')
  const [filterAction, setFilterAction] = useState('all')
  const [filterEntity, setFilterEntity] = useState('all')
  const [dateRange, setDateRange] = useState('7days')
  const [selectedLog, setSelectedLog] = useState<AuditLog | null>(null)

  useEffect(() => {
    fetchLogs()
  }, [dateRange, filterAction, filterEntity])

  const fetchLogs = async () => {
    setLoading(true)
    // Simulate API call
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // Mock data
    const mockLogs: AuditLog[] = [
      { id: '1', user: 'John Doe', action: 'CREATE', entity: 'news_article', entityId: 'art_123', ipAddress: '192.168.1.1', timestamp: '2026-01-31T10:30:00Z' },
      { id: '2', user: 'Jane Smith', action: 'UPDATE', entity: 'event', entityId: 'evt_456', changes: { title: 'Old Title -> New Title' }, ipAddress: '192.168.1.2', timestamp: '2026-01-31T09:15:00Z' },
      { id: '3', user: 'Admin User', action: 'DELETE', entity: 'user', entityId: 'usr_789', ipAddress: '192.168.1.3', timestamp: '2026-01-31T08:45:00Z' },
      { id: '4', user: 'John Doe', action: 'LOGIN', entity: 'auth', entityId: 'session_111', ipAddress: '192.168.1.1', timestamp: '2026-01-31T08:00:00Z' },
      { id: '5', user: 'Jane Smith', action: 'UPDATE', entity: 'news_article', entityId: 'art_222', changes: { isPublished: 'false -> true' }, ipAddress: '192.168.1.2', timestamp: '2026-01-30T16:30:00Z' },
      { id: '6', user: 'Admin User', action: 'CREATE', entity: 'user', entityId: 'usr_333', ipAddress: '192.168.1.3', timestamp: '2026-01-30T14:20:00Z' },
      { id: '7', user: 'John Doe', action: 'UPDATE', entity: 'page', entityId: 'page_444', ipAddress: '192.168.1.1', timestamp: '2026-01-30T11:00:00Z' },
      { id: '8', user: 'Jane Smith', action: 'DELETE', entity: 'event', entityId: 'evt_555', ipAddress: '192.168.1.2', timestamp: '2026-01-29T17:45:00Z' },
    ]
    
    setLogs(mockLogs)
    setLoading(false)
  }

  const getActionColor = (action: string) => {
    switch (action) {
      case 'CREATE': return 'bg-green-500/20 text-green-400'
      case 'UPDATE': return 'bg-blue-500/20 text-blue-400'
      case 'DELETE': return 'bg-red-500/20 text-red-400'
      case 'LOGIN': return 'bg-purple-500/20 text-purple-400'
      default: return 'bg-gray-500/20 text-gray-400'
    }
  }

  const filteredLogs = logs.filter(log => {
    const matchesSearch = log.user.toLowerCase().includes(searchTerm.toLowerCase()) || 
                         log.entity.toLowerCase().includes(searchTerm.toLowerCase())
    const matchesAction = filterAction === 'all' || log.action === filterAction
    const matchesEntity = filterEntity === 'all' || log.entity === filterEntity
    return matchesSearch && matchesAction && matchesEntity
  })

  if (loading) {
    return (
      <div className="flex items-center justify-center h-screen">
        <LoadingSpinner />
      </div>
    )
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold text-white mb-2">Audit Logs</h1>
          <p className="text-white/70">Track all system activities and changes</p>
        </div>
        <button className="flex items-center gap-2 px-4 py-2 bg-primary hover:bg-primary-dark text-white rounded-lg transition-all">
          <Download className="w-5 h-5" />
          Export Logs
        </button>
      </div>

      {/* Filters */}
      <div className="bg-white/10 backdrop-blur-xl rounded-xl p-6 border border-white/20">
        <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
          <div className="relative">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-white/50" />
            <input type="text" placeholder="Search logs..." value={searchTerm} onChange={(e) => setSearchTerm(e.target.value)}
              className="w-full pl-10 pr-4 py-2 bg-white/10 border border-white/20 rounded-lg text-white placeholder-white/40 focus:outline-none focus:ring-2 focus:ring-primary" />
          </div>

          <div className="relative">
            <Filter className="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-white/50" />
            <select value={filterAction} onChange={(e) => setFilterAction(e.target.value)}
              className="w-full pl-10 pr-4 py-2 bg-white/10 border border-white/20 rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-primary appearance-none">
              <option value="all">All Actions</option>
              <option value="CREATE">Create</option>
              <option value="UPDATE">Update</option>
              <option value="DELETE">Delete</option>
              <option value="LOGIN">Login</option>
            </select>
          </div>

          <div>
            <select value={filterEntity} onChange={(e) => setFilterEntity(e.target.value)}
              className="w-full px-4 py-2 bg-white/10 border border-white/20 rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-primary appearance-none">
              <option value="all">All Entities</option>
              <option value="news_article">News Articles</option>
              <option value="event">Events</option>
              <option value="user">Users</option>
              <option value="page">Pages</option>
            </select>
          </div>

          <div className="relative">
            <Calendar className="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-white/50" />
            <select value={dateRange} onChange={(e) => setDateRange(e.target.value)}
              className="w-full pl-10 pr-4 py-2 bg-white/10 border border-white/20 rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-primary appearance-none">
              <option value="24hours">Last 24 Hours</option>
              <option value="7days">Last 7 Days</option>
              <option value="30days">Last 30 Days</option>
              <option value="90days">Last 90 Days</option>
            </select>
          </div>
        </div>
      </div>

      {/* Logs Table */}
      <div className="bg-white/10 backdrop-blur-xl rounded-xl border border-white/20 overflow-hidden">
        <table className="w-full">
          <thead className="bg-white/5 border-b border-white/10">
            <tr>
              <th className="px-6 py-4 text-left text-sm font-semibold text-white">Timestamp</th>
              <th className="px-6 py-4 text-left text-sm font-semibold text-white">User</th>
              <th className="px-6 py-4 text-left text-sm font-semibold text-white">Action</th>
              <th className="px-6 py-4 text-left text-sm font-semibold text-white">Entity</th>
              <th className="px-6 py-4 text-left text-sm font-semibold text-white">IP Address</th>
              <th className="px-6 py-4 text-left text-sm font-semibold text-white">Details</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-white/10">
            {filteredLogs.map((log) => (
              <tr key={log.id} className="hover:bg-white/5 transition-colors">
                <td className="px-6 py-4">
                  <div className="text-white text-sm">
                    {new Date(log.timestamp).toLocaleString()}
                  </div>
                </td>
                <td className="px-6 py-4">
                  <div className="flex items-center gap-2">
                    <div className="w-8 h-8 bg-primary/30 rounded-full flex items-center justify-center">
                      <User className="w-4 h-4 text-white" />
                    </div>
                    <span className="text-white">{log.user}</span>
                  </div>
                </td>
                <td className="px-6 py-4">
                  <span className={`px-3 py-1 rounded-full text-xs font-medium ${getActionColor(log.action)}`}>
                    {log.action}
                  </span>
                </td>
                <td className="px-6 py-4 text-white">
                  {log.entity.replace('_', ' ').toUpperCase()}
                </td>
                <td className="px-6 py-4 text-white/70 text-sm font-mono">
                  {log.ipAddress}
                </td>
                <td className="px-6 py-4">
                  <button onClick={() => setSelectedLog(log)}
                    className="flex items-center gap-2 px-3 py-1 text-blue-400 hover:bg-blue-500/20 rounded-lg transition-all">
                    <Eye className="w-4 h-4" />
                    View
                  </button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {filteredLogs.length === 0 && (
        <div className="bg-white/10 backdrop-blur-xl rounded-xl p-12 text-center border border-white/20">
          <Activity className="w-16 h-16 text-white/30 mx-auto mb-4" />
          <p className="text-white/50">No audit logs found</p>
        </div>
      )}

      {/* Details Modal */}
      {selectedLog && (
        <div className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50" onClick={() => setSelectedLog(null)}>
          <div className="bg-white/10 backdrop-blur-xl rounded-xl p-6 border border-white/20 max-w-2xl w-full mx-4" onClick={e => e.stopPropagation()}>
            <h3 className="text-2xl font-bold text-white mb-4">Log Details</h3>
            <div className="space-y-3">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <p className="text-white/50 text-sm">User</p>
                  <p className="text-white font-medium">{selectedLog.user}</p>
                </div>
                <div>
                  <p className="text-white/50 text-sm">Action</p>
                  <span className={`inline-block px-3 py-1 rounded-full text-xs font-medium ${getActionColor(selectedLog.action)}`}>
                    {selectedLog.action}
                  </span>
                </div>
                <div>
                  <p className="text-white/50 text-sm">Entity</p>
                  <p className="text-white font-medium">{selectedLog.entity}</p>
                </div>
                <div>
                  <p className="text-white/50 text-sm">Entity ID</p>
                  <p className="text-white font-mono text-sm">{selectedLog.entityId}</p>
                </div>
                <div>
                  <p className="text-white/50 text-sm">IP Address</p>
                  <p className="text-white font-mono">{selectedLog.ipAddress}</p>
                </div>
                <div>
                  <p className="text-white/50 text-sm">Timestamp</p>
                  <p className="text-white">{new Date(selectedLog.timestamp).toLocaleString()}</p>
                </div>
              </div>
              {selectedLog.changes && (
                <div>
                  <p className="text-white/50 text-sm mb-2">Changes</p>
                  <div className="bg-white/5 rounded-lg p-4">
                    <pre className="text-white text-sm">{JSON.stringify(selectedLog.changes, null, 2)}</pre>
                  </div>
                </div>
              )}
            </div>
            <button onClick={() => setSelectedLog(null)}
              className="mt-6 w-full px-4 py-2 bg-white/10 hover:bg-white/20 text-white rounded-lg transition-all">
              Close
            </button>
          </div>
        </div>
      )}
    </div>
  )
}
