import { useState } from 'react'
import {
  ScrollText, FolderLock, Shield, UserCheck,
  UserX, Pencil, Trash2, Plus, RefreshCw,
  ChevronLeft, ChevronRight, Search, X,
  Loader2,
} from 'lucide-react'
import { useAuditLogs, useMe } from '@/hooks/useVault'
import type { AuditLog } from '@/services/api'
import { Button } from '@/components/ui/button'

// ── Action definitions ────────────────────────────────────────────────────────
// Each action gets an icon, human label, and colour treatment

type ActionDef = {
  label: string
  icon: React.ComponentType<{ className?: string }>
  iconCls: string
  badgeCls: string
}

const ACTION_MAP: Record<string, ActionDef> = {
  VAULT_CREATED: { label: 'Created vault',      icon: FolderLock, iconCls: 'text-blue-600',    badgeCls: 'bg-blue-50 text-blue-700 dark:bg-blue-950 dark:text-blue-300' },
  VAULT_UPDATED: { label: 'Renamed vault',       icon: Pencil,     iconCls: 'text-blue-500',    badgeCls: 'bg-blue-50 text-blue-700 dark:bg-blue-950 dark:text-blue-300' },
  VAULT_DELETED: { label: 'Deleted vault',       icon: Trash2,     iconCls: 'text-red-600',     badgeCls: 'bg-red-50 text-red-700 dark:bg-red-950 dark:text-red-300' },
  ENTRY_CREATED: { label: 'Added credential',    icon: Plus,       iconCls: 'text-green-600',   badgeCls: 'bg-green-50 text-green-700 dark:bg-green-950 dark:text-green-300' },
  ENTRY_UPDATED: { label: 'Updated credential',  icon: Pencil,     iconCls: 'text-amber-600',   badgeCls: 'bg-amber-50 text-amber-700 dark:bg-amber-950 dark:text-amber-300' },
  ENTRY_DELETED: { label: 'Deleted credential',  icon: Trash2,     iconCls: 'text-red-600',     badgeCls: 'bg-red-50 text-red-700 dark:bg-red-950 dark:text-red-300' },
  GRANT_CREATED: { label: 'Granted access',      icon: UserCheck,  iconCls: 'text-emerald-600', badgeCls: 'bg-emerald-50 text-emerald-700 dark:bg-emerald-950 dark:text-emerald-300' },
  GRANT_REVOKED: { label: 'Revoked access',      icon: UserX,      iconCls: 'text-orange-600',  badgeCls: 'bg-orange-50 text-orange-700 dark:bg-orange-950 dark:text-orange-300' },
  ENTRIES_VIEWED: { label: 'Viewed entries',     icon: Shield,     iconCls: 'text-slate-600',   badgeCls: 'bg-slate-100 text-slate-700 dark:bg-slate-900 dark:text-slate-300' },
}

function getActionDef(action: string): ActionDef {
  return ACTION_MAP[action] ?? {
    label: action.replace(/_/g, ' ').toLowerCase().replace(/^\w/, c => c.toUpperCase()),
    icon: RefreshCw,
    iconCls: 'text-slate-500',
    badgeCls: 'bg-slate-100 text-slate-600',
  }
}

// ── Module badge ──────────────────────────────────────────────────────────────

const MODULE_COLOURS: Record<string, string> = {
  vault: 'bg-blue-100 text-blue-700 dark:bg-blue-900 dark:text-blue-300',
  entry: 'bg-green-100 text-green-700 dark:bg-green-900 dark:text-green-300',
  grant: 'bg-amber-100 text-amber-700 dark:bg-amber-900 dark:text-amber-300',
}

function ModuleBadge({ module }: { module: string }) {
  const cls = MODULE_COLOURS[module.toLowerCase()] ?? 'text-muted-foreground'
  return (
    <span className={`inline-flex items-center px-2 py-0.5 rounded-md text-sm font-medium capitalize text-muted-foreground ${cls}`}>
      {module}
    </span>
  )
}

// ── Actor cell ────────────────────────────────────────────────────────────────

function ActorCell({ email }: { email: string }) {
  return (
    <div className='flex items-center min-w-0'>
      <div className='min-w-0'>
        <p className='text-sm font-medium text-muted-foreground leading-none truncate'>
          {email || '—'}
        </p>
      </div>
    </div>
  )
}

// ── Time helpers ──────────────────────────────────────────────────────────────

function formatDateTime(iso: string): string {
  return new Date(iso).toLocaleString(undefined, {
    year: 'numeric', month: 'short', day: 'numeric',
    hour: '2-digit', minute: '2-digit',
  })
}

function fullTimestamp(iso: string): string {
  return new Date(iso).toLocaleString(undefined, {
    year: 'numeric', month: 'short', day: 'numeric',
    hour: '2-digit', minute: '2-digit', second: '2-digit',
  })
}


// ── Empty state ───────────────────────────────────────────────────────────────

function EmptyState({ hasFilters, onClear }: { hasFilters: boolean; onClear: () => void }) {
  return (
    <tr>
      <td colSpan={5}>
        <div className='flex flex-col items-center justify-center py-4 gap-4 text-center'>
          <div className='rounded-full bg-muted p-4'>
            <ScrollText className='h-8 w-8 text-muted-foreground' />
          </div>
          <div>
            <p className='font-semibold text-foreground'>No audit events found</p>
            <p className='text-sm text-muted-foreground mt-1'>
              {hasFilters
                ? 'Try adjusting your filters or search term.'
                : 'Events will appear here as users interact with vaults.'}
            </p>
          </div>
          {hasFilters && (
            <Button
              variant="outline"
              onClick={onClear}
              className='inline-flex items-center gap-1.5 text-sm text-primary'
            >
              <X className='h-3.5 w-3.5' /> Clear filters
            </Button>
          )}
        </div>
      </td>
    </tr>
  )
}

// ── Main AuditPage ────────────────────────────────────────────────────────────

const PAGE_SIZE = 25

const ALL_MODULES = ['vault', 'entry', 'grant']
const ALL_ACTIONS = Object.keys(ACTION_MAP)

export function AuditPage() {
  const { data: me } = useMe()
  const [page, setPage]               = useState(1)
  const [search, setSearch]           = useState('')
  const [moduleFilter, setModule]     = useState('')
  const [actionFilter, setAction]     = useState('')

  const isAdmin = me?.role === 'admin'

  const { data, isLoading, error } = useAuditLogs({
    page,
    limit: PAGE_SIZE,
    module: moduleFilter || undefined,
    action: actionFilter || undefined,
    search: search || undefined,
  })

  // Access Denied State
  if (me && !isAdmin) {
    return (
      <div className='flex flex-col items-center justify-center min-h-full bg-background p-6 text-center'>
        <div className='rounded-full bg-destructive/10 p-6 mb-4'>
          <Shield className='h-12 w-12 text-destructive' />
        </div>
        <h1 className='text-2xl font-bold tracking-tight text-foreground'>Access Denied</h1>
        <p className='text-muted-foreground mt-2 max-w-sm'>
          Only administrators have permission to view the audit log.
        </p>
      </div>
    )
  }

  // Extract error message from axios error if possible
  const errorMessage = (error as any)?.response?.data?.details || (error as any)?.message

  const logs: AuditLog[]  = data?.logs ?? []
  const total: number     = data?.total ?? 0
  const totalPages        = data?.total_pages ?? 1
  const hasFilters        = !!(search || moduleFilter || actionFilter)

  const clearFilters = () => {
    setSearch(''); setModule(''); setAction(''); setPage(1)
  }

  const changePage = (n: number) => setPage(Math.max(1, Math.min(totalPages, n)))

  return (
    <div className='flex flex-col min-h-full bg-background'>

      {/* ── Page header ──────────────────────────────────────────────────── */}
      <div className='flex items-center justify-between px-6 py-4 border-b border-border'>
        <div className='flex flex-col items-start gap-1'>
          <h1 className='text-xl font-semibold tracking-tight text-foreground'>Audit Log</h1>
          <p className='text-muted-foreground text-sm'>Manage user activity and system events</p>
        </div>
      </div>

      {/* ── Search & Filters ────────────────────────────────────────────── */}
      <div className='flex items-center justify-between gap-3 px-6 py-4 flex-wrap'>
        {/* Search */}
        <div className='relative flex-1 min-w-[300px] max-w-sm'>
          <Search className='absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground pointer-events-none' />
          <input
            value={search}
            onChange={e => { setSearch(e.target.value); setPage(1) }}
            placeholder='Search by user or item...'
            className='h-9 w-full rounded-md border border-input bg-background pl-9 pr-3 text-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring text-foreground'
          />
          {search && (
            <button onClick={() => setSearch('')} className='absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground'>
              <X className='h-4 w-4' />
            </button>
          )}
        </div>

        <div className='flex items-center gap-2 flex-wrap'>
        {/* Module */}
        <select
          value={moduleFilter}
          onChange={e => { setModule(e.target.value); setPage(1) }}
          className='h-9 rounded-md border border-input bg-background px-3 text-sm text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring min-w-[140px]'
          >
          <option value=''>All modules</option>
          {ALL_MODULES.map(m => (
            <option key={m} value={m}>{m.charAt(0).toUpperCase() + m.slice(1)}</option>
          ))}
        </select>

        {/* Action */}
        <select
          value={actionFilter}
          onChange={e => { setAction(e.target.value); setPage(1) }}
          className='h-9 rounded-md border border-input bg-background px-3 text-sm text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring min-w-[140px]'
          >
          <option value=''>All actions</option>
          {ALL_ACTIONS.map(a => (
            <option key={a} value={a}>{getActionDef(a).label}</option>
          ))}
        </select>

        {/* Clear */}
        {hasFilters && (
          <Button
          variant="outline"
          onClick={clearFilters}
          className='inline-flex items-center gap-1.5 h-9 px-3 rounded-md text-sm text-muted-foreground hover:text-foreground transition-colors'
          >
            <X className='h-4 w-4' /> Clear
          </Button>
        )}
        </div>
      </div>

      {/* ── Table ────────────────────────────────────────────────────────── */}
      <div className='flex-1 px-6 py-6 overflow-x-auto'>
        <div className='rounded-xl border border-border bg-card overflow-hidden min-w-[800px]'>
          <table className='w-full text-xs'>
            <thead>
              <tr className='border-b border-border bg-muted/30'>
                <th className='h-12 px-4 text-left text-xs font-medium text-foreground   whitespace-nowrap'>
                  Action
                </th>
                <th className='h-12 px-4 text-left text-xs font-medium text-foreground  whitespace-nowrap'>
                  Module
                </th>
                <th className='h-12 px-4 text-left text-xs font-medium text-foreground  whitespace-nowrap'>
                  Performed By
                </th>
                <th className='h-12 px-4 text-left text-xs font-medium text-foreground  whitespace-nowrap'>
                  Item Details
                </th>
                <th className='h-12 px-4 text-right text-xs font-medium text-foreground  whitespace-nowrap'>
                  Performed On
                </th>
              </tr>
            </thead>
            <tbody className='divide-y divide-border'>
              {isLoading ? (
                 <div className='flex items-center justify-center py-4 text-center'>
                   <Loader2 className='h-4 w-4 animate-spin' />
                 </div>
              ) : errorMessage ? (
                <tr>
                  <td colSpan={5}>
                    <div className='flex flex-col items-center justify-center py-20 gap-3 text-center'>
                      <div className='rounded-full bg-destructive/10 p-4'>
                        <X className='h-6 w-6 text-destructive' />
                      </div>
                      <div>
                        <p className='font-semibold text-foreground'>Failed to load audit logs</p>
                        <p className='text-sm text-muted-foreground mt-1'>{errorMessage}</p>
                      </div>
                      <button 
                        onClick={() => window.location.reload()}
                        className='inline-flex items-center gap-1.5 h-9 px-4 rounded-md text-sm border border-input bg-background hover:bg-muted transition-colors'
                      >
                        <RefreshCw className="h-3.5 w-3.5" /> Retry
                      </button>
                    </div>
                  </td>
                </tr>
              ) : logs.length === 0 ? (
                <EmptyState hasFilters={hasFilters} onClear={clearFilters} />
              ) : (
                logs.map(log => {
                  const def  = getActionDef(log.action)
                  return (
                    <tr key={log.id} className='hover:bg-muted/20 transition-colors'>

                      {/* ── Action ───────────────────────────────────────── */}
                      <td className='px-4 py-4'>
                        <span className='inline-flex items-center gap-2.5'>
                          <span className='font-medium text-muted-foreground whitespace-nowrap text-sm'>
                            {def.label}
                          </span>
                        </span>
                      </td>

                      {/* ── Module ───────────────────────────────────────── */}
                      <td className='px-4 py-4'>
                        <ModuleBadge module={log.module} />
                      </td>

                      {/* ── Who ──────────────────────────────────────────── */}
                      <td className='px-4 py-4'>
                        <ActorCell email={log.actor_email || log.actor_name} />
                      </td>

                      {/* ── Item ─────────────────────────────────────────── */}
                      <td className='px-4 py-4 max-w-[200px]'>
                        {log.item_label ? (
                          <span className='text-muted-foreground font-medium truncate block text-sm' title={log.item_label}>
                            {log.item_label}
                          </span>
                        ) : (
                          <span className='text-muted-foreground font-mono text-sm'>
                            {log.item_id?.slice(0, 8)}…
                          </span>
                        )}
                      </td>

                      {/* ── When ─────────────────────────────────────────── */}
                      <td className='px-4 py-4 text-right'>
                        <span
                          className='text-sm text-muted-foreground whitespace-nowrap tabular-nums'
                          title={fullTimestamp(log.created_at)}
                        >
                          {formatDateTime(log.created_at)}
                        </span>
                      </td>

                    </tr>
                  )
                })
              )}
            </tbody>
          </table>
        </div>

        {/* ── Pagination ─────────────────────────────────────────────────── */}
        {totalPages > 1 && (
          <div className='flex items-center justify-between mt-6'>
            <p className='text-sm text-muted-foreground'>
              Showing{' '}
              <span className='font-medium text-foreground tabular-nums'>
                {((page - 1) * PAGE_SIZE) + 1}–{Math.min(page * PAGE_SIZE, total)}
              </span>{' '}
              of{' '}
              <span className='font-medium text-foreground tabular-nums'>
                {total.toLocaleString()}
              </span>
            </p>
            <div className='flex items-center gap-1.5'>
              <button
                onClick={() => changePage(page - 1)}
                disabled={page <= 1}
                className='inline-flex items-center gap-1 h-9 px-3 rounded-md text-sm border border-input bg-background hover:bg-muted disabled:opacity-40 disabled:pointer-events-none transition-colors'
              >
                <ChevronLeft className='h-4 w-4' />
                Previous
              </button>

              <div className='flex items-center gap-1'>
                {Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
                  const start = Math.max(1, Math.min(page - 2, totalPages - 4))
                  const n = start + i
                  if (n > totalPages) return null
                  return (
                    <button
                      key={n}
                      onClick={() => changePage(n)}
                      className={`h-9 w-9 rounded-md text-sm border transition-colors ${
                        n === page
                          ? 'border-primary bg-primary text-primary-foreground font-medium'
                          : 'border-input bg-background hover:bg-muted text-foreground'
                      }`}
                    >
                      {n}
                    </button>
                  )
                })}
              </div>

              <button
                onClick={() => changePage(page + 1)}
                disabled={page >= totalPages}
                className='inline-flex items-center gap-1 h-9 px-3 rounded-md text-sm border border-input bg-background hover:bg-muted disabled:opacity-40 disabled:pointer-events-none transition-colors'
              >
                Next
                <ChevronRight className='h-4 w-4' />
              </button>
            </div>
          </div>
        )}
      </div>
    </div>
  )
}
