import React, { useState, useMemo } from 'react';
import {
  Clock,
  Filter,
  Download,
  Search,
  AlertTriangle,
  Eye,
  FileText,
  Activity,
  X,
} from 'lucide-react';
import { Button, Card, Badge } from '../../../../components/ui';
import { AnalyticsPageLayout } from '../../../../components/analytics';
import { LoadingSpinner } from '../../../../components/ui';
import { useAllAuditLogs, useAllAuditLogStats } from '../../../../api/hooks/auditLogs';
import { useTenantId } from '../../../../hooks/useTenantId';
import { AuditLogFilters, AggregatedAuditLog } from '../../../../api/types/auditLogs';
import { auditLogsService } from '../../../../api/services/auditLogs';
import { EventFilterSidebar } from '../../../../components/analytics/events/EventFilterSidebar';
import { EventDetailModal } from '../../../../components/analytics/events/EventDetailModal';
import { EventStatsWidget } from '../../../../components/analytics/events/EventStatsWidget';
import { SeverityBadge } from '../../../../components/analytics/events/SeverityBadge';
import { ServiceBadge } from '../../../../components/analytics/events/ServiceBadge';
import { ActionBadge } from '../../../../components/analytics/events/ActionBadge';
import { formatDistanceToNow } from 'date-fns';

const EventRegistryPage: React.FC = () => {
  const tenantId = useTenantId();

  // UI State
  const [showFilters, setShowFilters] = useState(true);
  const [selectedEvent, setSelectedEvent] = useState<AggregatedAuditLog | null>(null);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(50);

  // Filter State
  const [filters, setFilters] = useState<AuditLogFilters>({
    limit: 50,
    offset: 0,
  });

  // Calculate pagination
  const paginatedFilters = useMemo(() => ({
    ...filters,
    limit: pageSize,
    offset: (currentPage - 1) * pageSize,
  }), [filters, currentPage, pageSize]);

  // Fetch audit logs
  const {
    data: auditLogs,
    isLoading: logsLoading,
    error: logsError,
    refetch: refetchLogs,
  } = useAllAuditLogs(tenantId, paginatedFilters, {
    enabled: !!tenantId,
    retry: 1,
    retryDelay: 1000,
  });

  // Fetch statistics
  const {
    data: stats,
    isLoading: statsLoading,
  } = useAllAuditLogStats(
    tenantId,
    {
      start_date: filters.start_date,
      end_date: filters.end_date,
    },
    {
      enabled: !!tenantId,
      retry: 1,
      retryDelay: 1000,
    }
  );

  // Handle filter changes
  const handleFilterChange = (newFilters: Partial<AuditLogFilters>) => {
    setFilters(prev => ({ ...prev, ...newFilters }));
    setCurrentPage(1); // Reset to first page when filters change
  };

  // Handle export
  const handleExport = async (format: 'csv' | 'json') => {
    if (!auditLogs || auditLogs.length === 0) return;

    try {
      auditLogsService.downloadAuditLogs(auditLogs, format);
    } catch (error) {
      console.error('Export failed:', error);
    }
  };

  // Format timestamp
  const formatTimestamp = (timestamp: string) => {
    try {
      return formatDistanceToNow(new Date(timestamp), { addSuffix: true });
    } catch {
      return timestamp;
    }
  };

  // Get total pages
  const totalPages = Math.ceil((auditLogs?.length || 0) / pageSize);

  return (
    <AnalyticsPageLayout
      title="Registro de Eventos"
      subtitle="Seguimiento de todas las actividades y eventos del sistema"
      icon={FileText}
    >
      {/* Statistics Widget */}
      {!statsLoading && stats && (
        <div className="mb-6">
          <EventStatsWidget stats={stats} />
        </div>
      )}

      {/* Controls Bar */}
      <Card className="p-4 mb-6 bg-gradient-to-r from-[var(--bg-primary)] to-[var(--bg-secondary)]">
        <div className="flex flex-wrap items-center justify-between gap-4">
          <div className="flex items-center gap-3">
            <Button
              variant={showFilters ? 'primary' : 'secondary'}
              size="sm"
              onClick={() => setShowFilters(!showFilters)}
              icon={Filter}
            >
              {showFilters ? 'Ocultar Filtros' : 'Mostrar Filtros'}
            </Button>

            {Object.keys(filters).length > 2 && (
              <Button
                variant="ghost"
                size="sm"
                onClick={() => {
                  setFilters({ limit: 50, offset: 0 });
                  setCurrentPage(1);
                }}
                icon={X}
              >
                Limpiar Filtros
              </Button>
            )}
          </div>

          <div className="flex items-center gap-2">
            <Button
              variant="secondary"
              size="sm"
              onClick={() => handleExport('csv')}
              icon={Download}
              disabled={!auditLogs || auditLogs.length === 0}
            >
              Exportar CSV
            </Button>
            <Button
              variant="secondary"
              size="sm"
              onClick={() => handleExport('json')}
              icon={Download}
              disabled={!auditLogs || auditLogs.length === 0}
            >
              Exportar JSON
            </Button>
          </div>
        </div>
      </Card>

      {/* Main Content */}
      <div className="flex gap-6">
        {/* Filter Sidebar */}
        {showFilters && (
          <div className="w-80 flex-shrink-0">
            <EventFilterSidebar
              filters={filters}
              onFiltersChange={handleFilterChange}
              stats={stats}
            />
          </div>
        )}

        {/* Event Table */}
        <div className="flex-1">
          <Card>
            {logsLoading ? (
              <div className="flex items-center justify-center py-16">
                <LoadingSpinner size="lg" />
              </div>
            ) : logsError ? (
              <div className="flex flex-col items-center justify-center py-16 text-center">
                <AlertTriangle className="mb-4 h-12 w-12 text-red-500" />
                <h3 className="mb-2 text-lg font-semibold text-gray-900">
                  Error al cargar eventos
                </h3>
                <p className="mb-4 text-sm text-gray-600">
                  Ocurrió un error al obtener los registros de auditoría
                </p>
                <Button onClick={() => refetchLogs()} size="sm">
                  Reintentar
                </Button>
              </div>
            ) : !auditLogs || auditLogs.length === 0 ? (
              <div className="flex flex-col items-center justify-center py-16 text-center">
                <Activity className="mb-4 h-12 w-12 text-gray-400" />
                <h3 className="mb-2 text-lg font-semibold text-gray-900">
                  No se encontraron eventos
                </h3>
                <p className="text-sm text-gray-600">
                  No hay registros de auditoría que coincidan con los filtros actuales
                </p>
              </div>
            ) : (
              <>
                {/* Table */}
                <div className="overflow-x-auto -mx-6">
                  <table className="w-full">
                    <thead className="border-b border-[var(--border-primary)] bg-[var(--bg-secondary)]">
                      <tr>
                        <th className="px-6 py-3 text-left text-xs font-semibold uppercase tracking-wider text-[var(--text-secondary)]">
                          Timestamp
                        </th>
                        <th className="px-6 py-3 text-left text-xs font-semibold uppercase tracking-wider text-[var(--text-secondary)]">
                          Servicio
                        </th>
                        <th className="px-6 py-3 text-left text-xs font-semibold uppercase tracking-wider text-[var(--text-secondary)]">
                          Acción
                        </th>
                        <th className="px-6 py-3 text-left text-xs font-semibold uppercase tracking-wider text-[var(--text-secondary)]">
                          Recurso
                        </th>
                        <th className="px-6 py-3 text-left text-xs font-semibold uppercase tracking-wider text-[var(--text-secondary)]">
                          Severidad
                        </th>
                        <th className="px-6 py-3 text-left text-xs font-semibold uppercase tracking-wider text-[var(--text-secondary)]">
                          Descripción
                        </th>
                        <th className="px-6 py-3 text-left text-xs font-semibold uppercase tracking-wider text-[var(--text-secondary)]">
                          Acciones
                        </th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-[var(--border-primary)] bg-[var(--bg-primary)]">
                      {auditLogs.map((event) => (
                        <tr
                          key={event.id}
                          className="hover:bg-[var(--bg-secondary)] transition-colors"
                        >
                          <td className="whitespace-nowrap px-6 py-4 text-sm text-gray-900">
                            <div className="flex flex-col">
                              <span className="font-medium">
                                {formatTimestamp(event.created_at)}
                              </span>
                              <span className="text-xs text-gray-500">
                                {new Date(event.created_at).toLocaleString()}
                              </span>
                            </div>
                          </td>
                          <td className="whitespace-nowrap px-6 py-4">
                            <ServiceBadge service={event.service_name} />
                          </td>
                          <td className="whitespace-nowrap px-6 py-4">
                            <ActionBadge action={event.action} />
                          </td>
                          <td className="px-6 py-4 text-sm">
                            <div className="flex flex-col">
                              <span className="font-medium text-gray-900">
                                {event.resource_type}
                              </span>
                              {event.resource_id && (
                                <span className="text-xs text-gray-500 truncate max-w-xs" title={event.resource_id}>
                                  {event.resource_id}
                                </span>
                              )}
                            </div>
                          </td>
                          <td className="whitespace-nowrap px-6 py-4">
                            <SeverityBadge severity={event.severity} />
                          </td>
                          <td className="px-6 py-4 text-sm text-gray-600">
                            <div className="max-w-md truncate" title={event.description}>
                              {event.description}
                            </div>
                          </td>
                          <td className="whitespace-nowrap px-6 py-4 text-sm">
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => setSelectedEvent(event)}
                              icon={Eye}
                            >
                              Ver
                            </Button>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>

                {/* Pagination */}
                <div className="border-t border-[var(--border-primary)] bg-[var(--bg-secondary)] px-6 py-4">
                  <div className="flex items-center justify-between">
                    <div className="text-sm text-[var(--text-secondary)]">
                      Mostrando{' '}
                      <span className="font-semibold text-[var(--text-primary)]">
                        {(currentPage - 1) * pageSize + 1}
                      </span>{' '}
                      a{' '}
                      <span className="font-semibold text-[var(--text-primary)]">
                        {Math.min(currentPage * pageSize, auditLogs.length)}
                      </span>{' '}
                      de{' '}
                      <span className="font-semibold text-[var(--text-primary)]">{auditLogs.length}</span>{' '}
                      eventos
                    </div>
                    <div className="flex items-center gap-3">
                      <Button
                        variant="secondary"
                        size="sm"
                        onClick={() => setCurrentPage(p => Math.max(1, p - 1))}
                        disabled={currentPage === 1}
                      >
                        ← Anterior
                      </Button>
                      <span className="text-sm font-medium text-[var(--text-primary)] px-3 py-1 bg-[var(--bg-primary)] rounded-lg">
                        Página {currentPage} de {totalPages}
                      </span>
                      <Button
                        variant="secondary"
                        size="sm"
                        onClick={() => setCurrentPage(p => Math.min(totalPages, p + 1))}
                        disabled={currentPage === totalPages}
                      >
                        Siguiente →
                      </Button>
                    </div>
                  </div>
                </div>
              </>
            )}
          </Card>
        </div>
      </div>

      {/* Event Detail Modal */}
      {selectedEvent && (
        <EventDetailModal
          event={selectedEvent}
          onClose={() => setSelectedEvent(null)}
        />
      )}
    </AnalyticsPageLayout>
  );
};

export default EventRegistryPage;
