/**
 * AuditLogViewer Component - View and export audit logs
 */

import { useState, useMemo, useEffect } from 'react'
import { useAdmin } from '../../contexts/AdminContext'
import Pagination from './Pagination'

export default function AuditLogViewer() {
  const { auditLogs, exportAuditLogs } = useAdmin()
  const [filter, setFilter] = useState<'all' | 'success' | 'failure'>('all')
  const [searchTerm, setSearchTerm] = useState('')
  const [currentPage, setCurrentPage] = useState(1)
  const [itemsPerPage, setItemsPerPage] = useState(25)

  const filteredLogs = useMemo(() => {
    return auditLogs.filter((log) => {
      if (filter !== 'all' && log.status !== filter) return false
      if (searchTerm) {
        const searchLower = searchTerm.toLowerCase()
        return (
          log.action.toLowerCase().includes(searchLower) ||
          log.user.toLowerCase().includes(searchLower) ||
          log.resourceType.toLowerCase().includes(searchLower) ||
          log.resourceId.toLowerCase().includes(searchLower)
        )
      }
      return true
    })
  }, [auditLogs, filter, searchTerm])

  // Pagination
  const totalPages = Math.ceil(filteredLogs.length / itemsPerPage)
  const paginatedLogs = useMemo(() => {
    const start = (currentPage - 1) * itemsPerPage
    const end = start + itemsPerPage
    return filteredLogs.slice(start, end)
  }, [filteredLogs, currentPage, itemsPerPage])

  // Reset to page 1 when filter or search changes
  useEffect(() => {
    setCurrentPage(1)
  }, [filter, searchTerm])

  const handleExport = () => {
    const data = exportAuditLogs()
    const blob = new Blob([data], { type: 'application/json' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `audit-logs-${Date.now()}.json`
    a.click()
    URL.revokeObjectURL(url)
  }

  return (
    <div className="bg-black/20 rounded-xl p-6 border border-white/10">
      <div className="flex justify-between items-center mb-4">
        <h2 className="text-xl font-bold text-white">Audit Logs</h2>
        <div className="flex gap-2">
          <button
            onClick={handleExport}
            className="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg font-semibold transition-colors"
          >
            Export JSON
          </button>
        </div>
      </div>

      <div className="mb-4 space-y-2">
        <input
          type="text"
          value={searchTerm}
          onChange={(e) => setSearchTerm(e.target.value)}
          placeholder="Search logs..."
          className="w-full px-4 py-2 bg-white/10 border border-white/20 rounded-lg text-white placeholder-white/40 focus:outline-none focus:border-blue-500"
        />
        <div className="flex gap-2">
          {(['all', 'success', 'failure'] as const).map((f) => (
            <button
              key={f}
              onClick={() => setFilter(f)}
              className={`px-3 py-1 rounded-lg text-sm font-semibold transition-colors ${
                filter === f
                  ? 'bg-blue-600 text-white'
                  : 'bg-white/10 text-white/70 hover:bg-white/20'
              }`}
            >
              {f.charAt(0).toUpperCase() + f.slice(1)}
            </button>
          ))}
        </div>
      </div>

      <div className="space-y-2">
        {paginatedLogs.length === 0 ? (
          <div className="text-center py-8 text-white/60">
            <p>No audit logs found</p>
          </div>
        ) : (
          <>
            <div className="space-y-2 max-h-96 overflow-y-auto">
              {paginatedLogs.map((log) => (
                <div
                  key={log.id}
                  className="bg-white/5 rounded-lg p-3 border border-white/10"
                >
                  <div className="flex justify-between items-start">
                    <div className="flex-1">
                      <div className="flex items-center gap-2 mb-1">
                        <span className="text-white font-semibold text-sm">{log.action}</span>
                        <span
                          className={`px-2 py-1 rounded text-xs ${
                            log.status === 'success'
                              ? 'bg-green-500/20 text-green-300'
                              : 'bg-red-500/20 text-red-300'
                          }`}
                        >
                          {log.status}
                        </span>
                      </div>
                      <p className="text-white/60 text-xs">
                        User: <span className="font-mono">{log.user.slice(0, 10)}...</span> |{' '}
                        {log.resourceType} | {log.resourceId.slice(0, 10)}...
                      </p>
                      {log.details && (
                        <p className="text-white/50 text-xs mt-1">
                          {JSON.stringify(log.details).slice(0, 100)}...
                        </p>
                      )}
                    </div>
                    <span className="text-white/50 text-xs">
                      {new Date(log.timestamp).toLocaleString()}
                    </span>
                  </div>
                </div>
              ))}
            </div>
            {filteredLogs.length > itemsPerPage && (
              <Pagination
                currentPage={currentPage}
                totalPages={totalPages}
                onPageChange={setCurrentPage}
                itemsPerPage={itemsPerPage}
                totalItems={filteredLogs.length}
                onItemsPerPageChange={setItemsPerPage}
              />
            )}
          </>
        )}
      </div>
    </div>
  )
}
