import { useState } from 'react';
import { Search, Filter, Calendar } from 'lucide-react';
import { PageHeader } from '@/components/common/PageHeader';
import { DataTable } from '@/components/common/DataTable';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { useAuditLogs } from '@/hooks/useAuditLogs';
import { AuditLogDTO } from '@/types/backend';
import { formatDateTime } from '@/utils/locale';
import { StatusBadge } from '@/components/common/StatusBadge';

const MODULES = [
  { value: '', label: 'Todos os módulos' },
  { value: 'ADMIN', label: 'Administração' },
  { value: 'ORG', label: 'Organização' },
  { value: 'RH', label: 'Recursos Humanos' },
  { value: 'BUDGET', label: 'Orçamento' },
  { value: 'TREASURY', label: 'Tesouraria' },
  { value: 'COMMON', label: 'Comum' },
];

export function AuditLogsPage() {
  const [moduleFilter, setModuleFilter] = useState<string>('');
  const [searchTerm, setSearchTerm] = useState('');

  const {
    logs,
    loading,
    error,
    page,
    totalPages,
    totalElements,
    refetch,
    setPage,
  } = useAuditLogs({
    page: 0,
    size: 20,
    sortBy: 'createdAt',
    sortDirection: 'DESC',
    module: moduleFilter || undefined,
  });

  const filteredLogs = logs.filter(
    (log) =>
      log.userUsername?.toLowerCase().includes(searchTerm.toLowerCase()) ||
      log.action?.toLowerCase().includes(searchTerm.toLowerCase()) ||
      log.entity?.toLowerCase().includes(searchTerm.toLowerCase()) ||
      log.description?.toLowerCase().includes(searchTerm.toLowerCase())
  );

  const getActionBadge = (action: string) => {
    const actionMap: Record<string, { variant: 'success' | 'warning' | 'info' | 'destructive' | 'default'; label: string }> = {
      CREATE: { variant: 'success', label: 'Criar' },
      UPDATE: { variant: 'info', label: 'Atualizar' },
      DELETE: { variant: 'destructive', label: 'Excluir' },
      VIEW: { variant: 'default', label: 'Visualizar' },
      LOGIN: { variant: 'success', label: 'Login' },
      LOGOUT: { variant: 'default', label: 'Logout' },
    };

    const config = actionMap[action] || { variant: 'default' as const, label: action };
    return <StatusBadge status={config.label.toLowerCase()} variant={config.variant} />;
  };

  const columns = [
    {
      key: 'createdAt',
      header: 'Data/Hora',
      cell: (log: AuditLogDTO) => (
        <div className="text-sm">
          {formatDateTime(log.createdAt)}
        </div>
      ),
    },
    {
      key: 'userUsername',
      header: 'Utilizador',
      cell: (log: AuditLogDTO) => (
        <div className="font-medium">{log.userUsername || 'N/A'}</div>
      ),
    },
    {
      key: 'module',
      header: 'Módulo',
      cell: (log: AuditLogDTO) => (
        <span className="text-sm">{log.module || '-'}</span>
      ),
    },
    {
      key: 'action',
      header: 'Ação',
      cell: (log: AuditLogDTO) => getActionBadge(log.action),
    },
    {
      key: 'entity',
      header: 'Entidade',
      cell: (log: AuditLogDTO) => (
        <div>
          <div className="font-medium">{log.entity}</div>
          {log.description && (
            <div className="text-xs text-muted-foreground truncate max-w-[200px]">
              {log.description}
            </div>
          )}
        </div>
      ),
    },
  ];

  return (
    <div className="space-y-6">
      <PageHeader
        title="Logs de Auditoria"
        description="Registo de todas as ações realizadas no sistema"
      />

      <div className="flex items-center gap-4">
        <div className="flex-1 max-w-sm">
          <div className="relative">
            <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
            <Input
              placeholder="Pesquisar por utilizador, ação ou entidade..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="pl-9"
            />
          </div>
        </div>
        <Select value={moduleFilter} onValueChange={setModuleFilter}>
          <SelectTrigger className="w-[200px]">
            <SelectValue placeholder="Filtrar por módulo" />
          </SelectTrigger>
          <SelectContent>
            {MODULES.map((mod) => (
              <SelectItem key={mod.value} value={mod.value}>
                {mod.label}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>

      {error && (
        <div className="gov-card p-4 text-destructive">
          {error}
        </div>
      )}
      <DataTable
        data={filteredLogs}
        columns={columns}
        isLoading={loading}
        emptyMessage="Nenhum log de auditoria encontrado"
        pageSize={20}
      />
    </div>
  );
}

