'use client'

import { useEffect, useState } from 'react'
import { getAuditLogs, AuditLog } from '@/lib/api/agent'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/Card'
import { Badge } from '@/components/ui/Badge'
import { Spinner } from '@/components/ui/Spinner'
import { Skeleton } from '@/components/ui/Skeleton'
import { EmptyState } from '@/components/ui/EmptyState'
import { ErrorState } from '@/components/ui/ErrorState'
import { formatRelativeTime } from '@/lib/types'
import { FileText, Search, Filter, RefreshCw, ChevronDown, ChevronUp, Eye } from 'lucide-react'
import { cn } from '@/lib/utils'

export default function AuditPage() {
  const [logs, setLogs] = useState<AuditLog[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [search, setSearch] = useState('')
  const [actionFilter, setActionFilter] = useState('')
  const [expanded, setExpanded] = useState<string | null>(null)

  useEffect(() => {
    let mounted = true
    async function load() {
      try {
        const res = await getAuditLogs({ limit: 200 })
        if (!res.success) throw new Error(res.message)
        if (mounted) setLogs(res.data.logs)
      } catch (err) {
        if (mounted) setError(err instanceof Error ? err.message : 'Failed to load audit logs')
      } finally {
        if (mounted) setLoading(false)
      }
    }
    load()
    const interval = setInterval(load, 15000)
    return () => { clearInterval(interval) }
  }, [])

  const filtered = logs.filter(log => {
    const matchesSearch = !search ||
      log.action.toLowerCase().includes(search.toLowerCase()) ||
      log.entity_type?.toLowerCase().includes(search.toLowerCase()) ||
      log.entity_id?.toLowerCase().includes(search.toLowerCase()) ||
      JSON.stringify(log.metadata).toLowerCase().includes(search.toLowerCase())
    const matchesAction = !actionFilter || log.action.includes(actionFilter)
    return matchesSearch && matchesAction
  })

  const actions = [...new Set(logs.map(l => l.action))].sort()

  if (loading) {
    return (
      <div className="space-y-6">
        <div><h1 className="text-2xl font-bold">Audit Log</h1></div>
        <Card><CardContent className="p-6"><div className="space-y-4">{Array.from({length:5}).map((_,i)=>(<div key={i} className="flex gap-4"><Skeleton className="h-10 w-10 rounded"/><div className="flex-1 space-y-2"><Skeleton className="h-4 w-1/2"/><Skeleton className="h-3 w-1/3"/></div></div>))}</div></CardContent></Card>
      </div>
    )
  }

  if (error) return <ErrorState message={error} onRetry={() => window.location.reload()} />

  return (
    <div className="space-y-6">
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold text-gray-900 dark:text-white">Audit Log</h1>
          <p className="text-gray-500 dark:text-gray-400">System-wide audit trail of all operations</p>
        </div>
        <div className="flex gap-2">
          <input
            type="text"
            placeholder="Search actions, entities, metadata..."
            value={search}
            onChange={e => setSearch(e.target.value)}
            className="h-10 w-64 rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500 dark:border-gray-600 dark:bg-gray-800"
          />
          <select
            value={actionFilter}
            onChange={e => setActionFilter(e.target.value)}
            className="h-10 rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500 dark:border-gray-600 dark:bg-gray-800"
          >
            <option value="">All Actions</option>
            {actions.map(a => <option key={a} value={a}>{a}</option>)}
          </select>
        </div>
      </div>

      <Card>
        <CardContent className="p-0">
          {filtered.length === 0 ? (
            <EmptyState icon={FileText} title="No audit logs" description={search || actionFilter ? 'Try adjusting your filters' : 'No audit records found'} />
          ) : (
            <div className="overflow-x-auto">
              <table className="w-full">
                <thead>
                  <tr className="border-b border-gray-200 dark:border-gray-700">
                    <th className="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Timestamp</th>
                    <th className="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Action</th>
                    <th className="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Business</th>
                    <th className="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Task</th>
                    <th className="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Order</th>
                    <th className="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Actor</th>
                    <th className="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Metadata</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-gray-200 dark:divide-gray-700">
                  {filtered.flatMap(log => [
                    <tr
                      key={log.id}
                      className="hover:bg-gray-50 dark:hover:bg-gray-800/50 cursor-pointer"
                      onClick={() => setExpanded(expanded === log.id ? null : log.id)}
                    >
                      <td className="px-4 py-3 text-sm text-gray-500 dark:text-gray-400 whitespace-nowrap">{formatRelativeTime(log.created_at)}</td>
                      <td className="px-4 py-3">
                        <Badge variant="secondary" className="text-xs">{log.action}</Badge>
                      </td>
                      <td className="px-4 py-3 text-sm text-gray-500 dark:text-gray-400 font-mono">{log.business_id.slice(0,8)}</td>
                      <td className="px-4 py-3 text-sm text-gray-500 dark:text-gray-400 font-mono">{log.task_id?.slice(0,8) || '—'}</td>
                      <td className="px-4 py-3 text-sm text-gray-500 dark:text-gray-400 font-mono">{log.entity_id?.slice(0,8) || '—'}</td>
                      <td className="px-4 py-3 text-sm text-gray-500 dark:text-gray-400">{log.user_id?.slice(0,8) || 'System'}</td>
                      <td className="px-4 py-3">
                        {log.metadata && Object.keys(log.metadata).length > 0 ? (
                          <button
                            onClick={e => { e.stopPropagation(); setExpanded(expanded === log.id ? null : log.id) }}
                            className="text-xs text-indigo-600 hover:underline"
                          >
                            {expanded === log.id ? 'Hide' : 'Show'} metadata
                          </button>
                        ) : (
                          <span className="text-xs text-gray-400">—</span>
                        )}
                      </td>
                    </tr>,
                    expanded === log.id && (
                      <tr key={`${log.id}-expanded`} className="bg-gray-50 dark:bg-gray-800/50">
                        <td colSpan={7} className="px-4 py-3">
                          <pre className="text-xs text-gray-600 dark:text-gray-400 overflow-auto max-h-40 p-3 rounded bg-gray-100 dark:bg-gray-900">
                            {JSON.stringify(log.metadata, null, 2)}
                          </pre>
                        </td>
                      </tr>
                    ),
                  ])}
                </tbody>
              </table>
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  )
}