'use client'

import { useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import axios from 'axios'
import { fmtDateTime, cn } from '@/lib/utils'
import { Activity, Search, Filter } from 'lucide-react'
import { Card, Badge, PageHeader, Pagination } from '@/components/ui/components'

const ACTION_COLORS: Record<string, string> = {
  CREATE: 'success', UPDATE: 'info', DELETE: 'danger', APPROVE: 'success',
  DECLINE: 'danger', DISBURSE: 'info', REPAY: 'success', LOGIN: 'default',
  LOGOUT: 'default', EXPORT: 'default', IMPORT: 'warning',
}

export default function AuditLogsPage() {
  const [search, setSearch]   = useState('')
  const [module, setModule]   = useState('')
  const [action, setAction]   = useState('')
  const [dateFrom, setDateFrom] = useState('')
  const [dateTo, setDateTo]     = useState('')
  const [page, setPage]       = useState(1)
  const pageSize = 30

  const { data, isLoading } = useQuery({
    queryKey: ['audit-logs', { search, module, action, dateFrom, dateTo, page }],
    queryFn: () => {
      const p = new URLSearchParams({ page: String(page), pageSize: String(pageSize) })
      if (search)   p.set('search',   search)
      if (module)   p.set('module',   module)
      if (action)   p.set('action',   action)
      if (dateFrom) p.set('dateFrom', dateFrom)
      if (dateTo)   p.set('dateTo',   dateTo)
      return axios.get(`/api/admin/audit?${p}`).then(r => r.data)
    },
    placeholderData: (prev: unknown) => prev,
  })

  const logs  = data?.data ?? []
  const total = data?.total ?? 0
  const pages = Math.ceil(total / pageSize)

  const MODULES = ['','members','loans','savings','accounting','collections','payroll','reports','configuration','admin','groups','auth']
  const ACTIONS = ['','CREATE','UPDATE','DELETE','APPROVE','DECLINE','DISBURSE','REPAY','LOGIN','LOGOUT','EXPORT','IMPORT']

  return (
    <div className="p-6 space-y-5 max-w-screen-2xl mx-auto">
      <PageHeader
        title="Audit Trail"
        description={`${total.toLocaleString()} log entries`}
        icon={<Activity className="w-6 h-6" />}
      />

      {/* Filters */}
      <div className="bg-card border rounded-xl p-4 flex flex-wrap gap-3">
        <div className="relative flex-1 min-w-[200px]">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
          <input value={search} onChange={e => { setSearch(e.target.value); setPage(1) }}
            placeholder="Search user, record, description…"
            className="w-full pl-9 pr-4 py-2 text-sm border rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/20 bg-background"
          />
        </div>
        <select value={module} onChange={e => { setModule(e.target.value); setPage(1) }} className="px-3 py-2 text-sm border rounded-lg bg-background">
          <option value="">All Modules</option>
          {MODULES.filter(Boolean).map(m => <option key={m} value={m}>{m}</option>)}
        </select>
        <select value={action} onChange={e => { setAction(e.target.value); setPage(1) }} className="px-3 py-2 text-sm border rounded-lg bg-background">
          <option value="">All Actions</option>
          {ACTIONS.filter(Boolean).map(a => <option key={a} value={a}>{a}</option>)}
        </select>
        <input type="date" value={dateFrom} onChange={e => { setDateFrom(e.target.value); setPage(1) }} className="px-3 py-2 text-sm border rounded-lg bg-background" />
        <input type="date" value={dateTo}   onChange={e => { setDateTo(e.target.value);   setPage(1) }} className="px-3 py-2 text-sm border rounded-lg bg-background" />
      </div>

      <Card>
        <div className="overflow-x-auto">
          <table className="table-lms w-full text-xs">
            <thead>
              <tr>
                <th>Timestamp</th><th>User</th><th>Action</th><th>Module</th>
                <th>Record</th><th>Description</th><th>IP Address</th>
              </tr>
            </thead>
            <tbody>
              {isLoading
                ? Array.from({ length: 15 }).map((_, i) => (
                    <tr key={i}>{Array.from({ length: 7 }).map((_, j) => <td key={j}><div className="h-4 bg-muted rounded animate-pulse" /></td>)}</tr>
                  ))
                : logs.length === 0
                  ? <tr><td colSpan={7} className="text-center py-10 text-muted-foreground">No audit logs found</td></tr>
                  : logs.map((l: any) => (
                    <tr key={l.id} className="hover:bg-accent/30">
                      <td className="text-muted-foreground whitespace-nowrap">{fmtDateTime(l.createdAt)}</td>
                      <td>
                        <p className="font-medium">{l.userFullName}</p>
                        <p className="text-muted-foreground">{l.userEmail}</p>
                      </td>
                      <td>
                        <Badge variant={(ACTION_COLORS[l.action] ?? 'default') as any}>{l.action}</Badge>
                      </td>
                      <td className="capitalize">{l.module}</td>
                      <td>
                        {l.recordType && <p className="font-medium">{l.recordType}</p>}
                        {l.recordRef && <p className="text-muted-foreground font-mono">{l.recordRef}</p>}
                      </td>
                      <td className="max-w-[300px]">
                        <p className="truncate">{l.description}</p>
                        {l.changedFields?.length > 0 && (
                          <p className="text-muted-foreground text-xs">Changed: {l.changedFields.slice(0, 5).join(', ')}</p>
                        )}
                      </td>
                      <td className="text-muted-foreground font-mono">{l.ipAddress}</td>
                    </tr>
                  ))
              }
            </tbody>
          </table>
        </div>
        <Pagination page={page} pages={pages} total={total} pageSize={pageSize} onPage={setPage} />
      </Card>
    </div>
  )
}
