'use client'

import { useState } from 'react'
import {
  Search,
  Filter,
  Eye,
  CheckCircle2,
  XCircle,
  Download,
  ChevronDown,
} from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import useSWR from 'swr'
import { formatDate, getActionLabel } from '@/lib/utils-ad'
import type { AuditLog } from '@/lib/types'
import { useAuth } from '@/lib/auth-context'
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuCheckboxItem,
  DropdownMenuTrigger,
  DropdownMenuSeparator,
  DropdownMenuLabel,
} from '@/components/ui/dropdown-menu'
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
} from '@/components/ui/dialog'
import { cn } from '@/lib/utils'

import { arrayFetcher } from '@/lib/fetcher'

const fetcher = (url: string) =>
  fetch(url).then((r) => r.json()).then((d) => (Array.isArray(d) ? d : d))

const ACTION_CATEGORIES = [
  { value: 'user', label: 'Usuários AD' },
  { value: 'group', label: 'Grupos AD' },
  { value: 'tenant', label: 'Tenants' },
  { value: 'portal_user', label: 'Usuários do Portal' },
  { value: 'agent', label: 'Agente' },
  { value: 'sync', label: 'Sincronização' },
  { value: 'auth', label: 'Autenticação' },
]

export default function AuditPage() {
  const { user } = useAuth()
  const isAdmin = user?.role === 'admin_global'

  const [search, setSearch] = useState('')
  const [selectedTenants, setSelectedTenants] = useState<string[]>([])
  const [selectedStatuses, setSelectedStatuses] = useState<string[]>([])
  const [selectedCategories, setSelectedCategories] = useState<string[]>([])
  const [page, setPage] = useState(1)
  const [detailLog, setDetailLog] = useState<any | null>(null)

  const { data: tenantsList = [] } = useSWR(isAdmin ? '/api/tenants' : null, arrayFetcher)

  const PAGE_SIZE = 50

  const params = new URLSearchParams({ page: String(page), limit: String(PAGE_SIZE) })
  if (search) params.set('search', search)
  if (selectedTenants.length === 1) params.set('tenant_id', selectedTenants[0])

  const { data, isLoading } = useSWR(`/api/audit?${params}`, fetcher, { refreshInterval: 30000 })
  const rawLogs: any[] = data?.data ?? []
  const total = data?.total ?? 0

  const allLogs = rawLogs.map((l) => ({
    ...l,
    id: String(l.id),
    tenantId: l.tenant_id ? String(l.tenant_id) : null,
    tenantName: l.tenant_name ?? null,
    userName: l.performed_by,
    objectName: l.target ?? '',
    details: l.action,
    status: 'success',
    createdAt: l.created_at,
    ipAddress: l.ip_address,
  }))

  const filtered = allLogs.filter((l) => {
    const matchStatus = selectedStatuses.length === 0 || selectedStatuses.includes(l.status)
    const matchCategory = selectedCategories.length === 0 || selectedCategories.some((c) => l.action?.startsWith(c))
    return matchStatus && matchCategory
  })

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

  function handleSearch(v: string) {
    setSearch(v)
    setPage(1)
  }

  function toggleFilter<T extends string>(
    list: T[],
    setList: (v: T[]) => void,
    value: T,
  ) {
    setList(
      list.includes(value) ? list.filter((x) => x !== value) : [...list, value],
    )
    setPage(1)
  }

  const activeFilters =
    selectedTenants.length + selectedStatuses.length + selectedCategories.length

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-xl font-bold text-foreground">Auditoria</h2>
          <p className="text-sm text-muted-foreground">
            {filtered.length} registro(s) encontrado(s)
          </p>
        </div>
        <Button variant="outline" size="sm">
          <Download className="w-4 h-4 mr-2" />
          Exportar CSV
        </Button>
      </div>

      {/* Filtros */}
      <div className="flex items-center gap-3 flex-wrap">
        <div className="relative flex-1 min-w-64">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
          <Input
            placeholder="Pesquisar por ação, usuário, objeto..."
            value={search}
            onChange={(e) => handleSearch(e.target.value)}
            className="pl-9"
          />
        </div>

        {/* Filtro status */}
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button variant="outline" size="sm">
              <Filter className="w-4 h-4 mr-2" />
              Status
              {selectedStatuses.length > 0 && (
                <span className="ml-1.5 w-4 h-4 rounded-full bg-primary text-primary-foreground text-xs flex items-center justify-center">
                  {selectedStatuses.length}
                </span>
              )}
              <ChevronDown className="w-3 h-3 ml-2" />
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent>
            <DropdownMenuLabel>Status</DropdownMenuLabel>
            <DropdownMenuSeparator />
            {['success', 'error'].map((s) => (
              <DropdownMenuCheckboxItem
                key={s}
                checked={selectedStatuses.includes(s)}
                onCheckedChange={() => toggleFilter(selectedStatuses, setSelectedStatuses, s)}
              >
                <span className={cn(
                  'inline-flex items-center gap-1.5',
                  s === 'success' ? 'text-green-700' : 'text-red-700'
                )}>
                  {s === 'success' ? <CheckCircle2 className="w-3.5 h-3.5" /> : <XCircle className="w-3.5 h-3.5" />}
                  {s === 'success' ? 'Sucesso' : 'Erro'}
                </span>
              </DropdownMenuCheckboxItem>
            ))}
          </DropdownMenuContent>
        </DropdownMenu>

        {/* Filtro categoria */}
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button variant="outline" size="sm">
              <Filter className="w-4 h-4 mr-2" />
              Categoria
              {selectedCategories.length > 0 && (
                <span className="ml-1.5 w-4 h-4 rounded-full bg-primary text-primary-foreground text-xs flex items-center justify-center">
                  {selectedCategories.length}
                </span>
              )}
              <ChevronDown className="w-3 h-3 ml-2" />
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent>
            <DropdownMenuLabel>Categoria</DropdownMenuLabel>
            <DropdownMenuSeparator />
            {ACTION_CATEGORIES.map((c) => (
              <DropdownMenuCheckboxItem
                key={c.value}
                checked={selectedCategories.includes(c.value)}
                onCheckedChange={() =>
                  toggleFilter(selectedCategories, setSelectedCategories, c.value)
                }
              >
                {c.label}
              </DropdownMenuCheckboxItem>
            ))}
          </DropdownMenuContent>
        </DropdownMenu>

        {/* Filtro tenant (apenas admin global) */}
        {isAdmin && (
          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <Button variant="outline" size="sm">
                <Filter className="w-4 h-4 mr-2" />
                Empresa
                {selectedTenants.length > 0 && (
                  <span className="ml-1.5 w-4 h-4 rounded-full bg-primary text-primary-foreground text-xs flex items-center justify-center">
                    {selectedTenants.length}
                  </span>
                )}
                <ChevronDown className="w-3 h-3 ml-2" />
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent className="w-64">
              <DropdownMenuLabel>Empresa</DropdownMenuLabel>
              <DropdownMenuSeparator />
              {tenantsList.map((t: any) => (
                <DropdownMenuCheckboxItem
                  key={t.id}
                  checked={selectedTenants.includes(t.id)}
                  onCheckedChange={() =>
                    toggleFilter(selectedTenants, setSelectedTenants, t.id)
                  }
                >
                  {t.name}
                </DropdownMenuCheckboxItem>
              ))}
            </DropdownMenuContent>
          </DropdownMenu>
        )}

        {activeFilters > 0 && (
          <Button
            variant="ghost"
            size="sm"
            onClick={() => {
              setSelectedTenants([])
              setSelectedStatuses([])
              setSelectedCategories([])
              setPage(1)
            }}
            className="text-muted-foreground"
          >
            Limpar filtros
          </Button>
        )}
      </div>

      {/* Tabela */}
      <div className="bg-card border border-border rounded-xl overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead className="bg-muted/50 border-b border-border">
              <tr>
                {['Data/Hora', 'Ação', 'Objeto', 'Usuário', isAdmin ? 'Empresa' : '', 'Status', ''].map(
                  (h) =>
                    h && (
                      <th
                        key={h}
                        className="px-4 py-3 text-left text-xs font-semibold text-muted-foreground uppercase tracking-wide"
                      >
                        {h}
                      </th>
                    ),
                )}
              </tr>
            </thead>
            <tbody className="bg-card divide-y divide-border">
              {paginated.length === 0 ? (
                <tr>
                  <td
                    colSpan={7}
                    className="px-4 py-10 text-center text-sm text-muted-foreground"
                  >
                    Nenhum registro encontrado.
                  </td>
                </tr>
              ) : (
                paginated.map((log) => (
                  <tr
                    key={log.id}
                    className="hover:bg-muted/30 transition-colors cursor-pointer"
                    onClick={() => setDetailLog(log)}
                  >
                    <td className="px-4 py-3 text-xs text-muted-foreground whitespace-nowrap">
                      {formatDate(log.createdAt)}
                    </td>
                    <td className="px-4 py-3">
                      <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-muted text-muted-foreground font-mono">
                        {log.action}
                      </span>
                    </td>
                    <td className="px-4 py-3">
                      <p className="font-medium text-foreground text-sm">{log.objectName}</p>
                      <p className="text-xs text-muted-foreground">{log.objectType}</p>
                    </td>
                    <td className="px-4 py-3 text-sm text-muted-foreground whitespace-nowrap">
                      {log.userName}
                    </td>
                    {isAdmin && (
                      <td className="px-4 py-3 text-sm text-muted-foreground">
                        {log.tenantName ?? <span className="italic text-xs">Admin Global</span>}
                      </td>
                    )}
                    <td className="px-4 py-3">
                      {log.status === 'success' ? (
                        <span className="inline-flex items-center gap-1.5 px-2 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">
                          <CheckCircle2 className="w-3 h-3" />
                          Sucesso
                        </span>
                      ) : (
                        <span className="inline-flex items-center gap-1.5 px-2 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800">
                          <XCircle className="w-3 h-3" />
                          Erro
                        </span>
                      )}
                    </td>
                    <td className="px-4 py-3">
                      <Eye className="w-4 h-4 text-muted-foreground" />
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>

        {/* Paginação */}
        {totalPages > 1 && (
          <div className="flex items-center justify-between px-4 py-3 border-t border-border text-sm text-muted-foreground">
            <span>
              {(page - 1) * PAGE_SIZE + 1}–{Math.min(page * PAGE_SIZE, filtered.length)} de{' '}
              {filtered.length}
            </span>
            <div className="flex gap-1">
              <Button
                variant="outline"
                size="sm"
                onClick={() => setPage((p) => Math.max(1, p - 1))}
                disabled={page === 1}
              >
                Anterior
              </Button>
              <Button
                variant="outline"
                size="sm"
                onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
                disabled={page === totalPages}
              >
                Próximo
              </Button>
            </div>
          </div>
        )}
      </div>

      {/* Modal detalhe */}
      <Dialog open={!!detailLog} onOpenChange={() => setDetailLog(null)}>
        <DialogContent className="sm:max-w-lg">
          <DialogHeader>
            <DialogTitle>Detalhe do Log</DialogTitle>
            <DialogDescription>
              {detailLog && formatDate(detailLog.createdAt)}
            </DialogDescription>
          </DialogHeader>
          {detailLog && (
            <div className="space-y-4 text-sm">
              <div className="grid grid-cols-2 gap-3">
                {[
                  { label: 'Ação', value: detailLog.action },
                  { label: 'Status', value: detailLog.status === 'success' ? 'Sucesso' : 'Erro' },
                  { label: 'Usuário', value: detailLog.userName },
                  { label: 'IP', value: detailLog.ipAddress },
                  { label: 'Objeto', value: `${detailLog.objectType}: ${detailLog.objectName}` },
                  { label: 'Empresa', value: detailLog.tenantName ?? 'Admin Global' },
                ].map((f) => (
                  <div key={f.label}>
                    <p className="text-xs text-muted-foreground font-semibold uppercase tracking-wide">{f.label}</p>
                    <p className="text-foreground mt-0.5 break-all font-mono text-xs">{f.value}</p>
                  </div>
                ))}
              </div>

              <div>
                <p className="text-xs text-muted-foreground font-semibold uppercase tracking-wide mb-1">Descrição</p>
                <p className="text-foreground">{detailLog.details}</p>
              </div>

              {detailLog.taskId && (
                <div>
                  <p className="text-xs text-muted-foreground font-semibold uppercase tracking-wide mb-1">Task ID</p>
                  <p className="text-foreground font-mono text-xs">{detailLog.taskId}</p>
                </div>
              )}

              {detailLog.agentResponse && (
                <div>
                  <p className="text-xs text-muted-foreground font-semibold uppercase tracking-wide mb-1">Resposta do Agente</p>
                  <pre className="text-xs font-mono bg-muted rounded-lg p-3 overflow-x-auto text-foreground whitespace-pre-wrap">
                    {JSON.stringify(JSON.parse(detailLog.agentResponse), null, 2)}
                  </pre>
                </div>
              )}
            </div>
          )}
        </DialogContent>
      </Dialog>
    </div>
  )
}
