'use client'

import { useEffect, useState, useCallback } from 'react'
import AuditLogTable, { AuditLogRow } from '@/components/pitch-admin/AuditLogTable'

const ACTIONS = [
  '', // any
  'login_success',
  'login_failed',
  'logout',
  'admin_login_success',
  'admin_login_failed',
  'admin_logout',
  'slide_viewed',
  'assumption_changed',
  'assumption_edited',
  'scenario_edited',
  'investor_invited',
  'magic_link_resent',
  'investor_revoked',
  'investor_edited',
  'admin_created',
  'admin_edited',
  'admin_deactivated',
  'new_ip_detected',
]

const PAGE_SIZE = 50

export default function AuditPage() {
  const [logs, setLogs] = useState<AuditLogRow[]>([])
  const [total, setTotal] = useState(0)
  const [loading, setLoading] = useState(true)
  const [actorType, setActorType] = useState('')
  const [action, setAction] = useState('')
  const [page, setPage] = useState(0)

  const load = useCallback(async () => {
    setLoading(true)
    const params = new URLSearchParams()
    if (actorType) params.set('actor_type', actorType)
    if (action) params.set('action', action)
    params.set('limit', String(PAGE_SIZE))
    params.set('offset', String(page * PAGE_SIZE))

    const res = await fetch(`/api/admin/audit-logs?${params.toString()}`)
    if (res.ok) {
      const data = await res.json()
      setLogs(data.logs)
      setTotal(data.total)
    }
    setLoading(false)
  }, [actorType, action, page])

  useEffect(() => { load() }, [load])

  const totalPages = Math.max(1, Math.ceil(total / PAGE_SIZE))

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-semibold text-white">Audit Log</h1>
        <p className="text-sm text-white/50 mt-1">{total} total events</p>
      </div>

      <div className="flex items-center gap-3 flex-wrap">
        <select
          value={actorType}
          onChange={(e) => { setActorType(e.target.value); setPage(0) }}
          className="bg-white/[0.04] border border-white/[0.08] rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:ring-2 focus:ring-indigo-500/40"
        >
          <option value="">All actors</option>
          <option value="admin">Admins only</option>
          <option value="investor">Investors only</option>
        </select>
        <select
          value={action}
          onChange={(e) => { setAction(e.target.value); setPage(0) }}
          className="bg-white/[0.04] border border-white/[0.08] rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:ring-2 focus:ring-indigo-500/40 max-w-[260px]"
        >
          {ACTIONS.map(a => (
            <option key={a} value={a}>{a || 'All actions'}</option>
          ))}
        </select>
        {(actorType || action) && (
          <button
            onClick={() => { setActorType(''); setAction(''); setPage(0) }}
            className="text-sm text-white/50 hover:text-white px-3 py-2"
          >
            Clear filters
          </button>
        )}
      </div>

      <div className="bg-white/[0.04] border border-white/[0.06] rounded-2xl p-5">
        {loading ? (
          <div className="flex items-center justify-center h-32">
            <div className="w-6 h-6 border-2 border-indigo-500 border-t-transparent rounded-full animate-spin" />
          </div>
        ) : (
          <AuditLogTable rows={logs} showActor />
        )}
      </div>

      {totalPages > 1 && (
        <div className="flex items-center justify-between text-sm">
          <div className="text-white/50">
            Page {page + 1} of {totalPages}
          </div>
          <div className="flex items-center gap-2">
            <button
              onClick={() => setPage(p => Math.max(0, p - 1))}
              disabled={page === 0}
              className="bg-white/[0.06] hover:bg-white/[0.1] text-white px-3 py-1.5 rounded-lg disabled:opacity-30"
            >
              Previous
            </button>
            <button
              onClick={() => setPage(p => Math.min(totalPages - 1, p + 1))}
              disabled={page >= totalPages - 1}
              className="bg-white/[0.06] hover:bg-white/[0.1] text-white px-3 py-1.5 rounded-lg disabled:opacity-30"
            >
              Next
            </button>
          </div>
        </div>
      )}
    </div>
  )
}
