import React, { useState, useMemo, useCallback, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { Card, CardHeader, CardBody } from '../../ui/Card';
import { SeverityBadge } from '../../ui/Badge';
import { Button } from '../../ui/Button';
import { useNotifications } from '../../../hooks/useNotifications';
import { useAlertFilters } from '../../../hooks/useAlertFilters';
import { useAlertGrouping, type GroupingMode } from '../../../hooks/useAlertGrouping';
import { useAlertAnalytics, useAlertAnalyticsTracking } from '../../../hooks/useAlertAnalytics';
import { useKeyboardNavigation } from '../../../hooks/useKeyboardNavigation';
import { filterAlerts, getAlertStatistics, getTimeGroup } from '../../../utils/alertHelpers';
import {
  Bell,
  Wifi,
  WifiOff,
  CheckCircle,
  BarChart3,
  AlertTriangle,
  AlertCircle,
  Clock,
  ChevronLeft,
  ChevronRight,
} from 'lucide-react';
import AlertFilters from './AlertFilters';
import AlertGroupHeader from './AlertGroupHeader';
import AlertCard from './AlertCard';
import AlertTrends from './AlertTrends';
import AlertBulkActions from './AlertBulkActions';

export interface RealTimeAlertsProps {
  className?: string;
  maxAlerts?: number;
  showAnalytics?: boolean;
  showGrouping?: boolean;
}

/**
 * RealTimeAlerts - Dashboard component for displaying today's active alerts
 *
 * IMPORTANT: This component shows ONLY TODAY'S alerts (from 00:00 UTC today onwards)
 * to prevent flooding the dashboard with historical data.
 *
 * For historical alert data, use the Analytics panel or API endpoints:
 * - showAnalytics=true: Shows AlertTrends component with historical data (7 days, 30 days, etc.)
 * - API: /api/v1/tenants/{tenant_id}/alerts/analytics for historical analytics
 *
 * Alert scopes across the application:
 * - Dashboard (this component): TODAY'S alerts only
 * - Notification Bell: Last 24 hours
 * - Analytics Panel: Historical data (configurable: 7 days, 30 days, etc.)
 * - localStorage: Auto-cleanup of alerts >24h old on load
 * - Redis cache (initial_items): TODAY'S alerts only
 */
const RealTimeAlerts: React.FC<RealTimeAlertsProps> = ({
  className,
  maxAlerts = 50,
  showAnalytics = true,
  showGrouping = true,
}) => {
  const { t } = useTranslation(['dashboard']);
  const [expandedAlerts, setExpandedAlerts] = useState<Set<string>>(new Set());
  const [selectedAlerts, setSelectedAlerts] = useState<Set<string>>(new Set());
  const [showBulkActions, setShowBulkActions] = useState(false);
  const [showAnalyticsPanel, setShowAnalyticsPanel] = useState(false);

  // Pagination state
  const ALERTS_PER_PAGE = 3;
  const [currentPage, setCurrentPage] = useState(1);

  const {
    notifications,
    isConnected,
    markAsRead,
    removeNotification,
    snoozeAlert,
    unsnoozeAlert,
    isAlertSnoozed,
    snoozedAlerts,
    markMultipleAsRead,
    removeMultiple,
    snoozeMultiple,
  } = useNotifications();

  const {
    filters,
    toggleSeverity,
    toggleCategory,
    setTimeRange,
    setSearch,
    toggleShowSnoozed,
    clearFilters,
    hasActiveFilters,
    activeFilterCount,
  } = useAlertFilters();

  // Dashboard shows only TODAY's alerts
  // Analytics panel shows historical data (configured separately)
  const filteredNotifications = useMemo(() => {
    // Filter to today's alerts only for dashboard display
    // This prevents showing yesterday's or older alerts on the main dashboard
    const todayAlerts = notifications.filter(alert => {
      const timeGroup = getTimeGroup(alert.timestamp);
      return timeGroup === 'today';
    });

    return filterAlerts(todayAlerts, filters, snoozedAlerts).slice(0, maxAlerts);
  }, [notifications, filters, snoozedAlerts, maxAlerts]);

  const {
    groupedAlerts,
    groupingMode,
    setGroupingMode,
    toggleGroupCollapse,
    isGroupCollapsed,
  } = useAlertGrouping(filteredNotifications, 'time');

  const analytics = useAlertAnalytics(notifications);
  const { trackAcknowledgment, trackResolution } = useAlertAnalyticsTracking();

  const stats = useMemo(() => {
    return getAlertStatistics(filteredNotifications, snoozedAlerts);
  }, [filteredNotifications, snoozedAlerts]);

  const flatAlerts = useMemo(() => {
    return groupedAlerts.flatMap(group =>
      isGroupCollapsed(group.id) ? [] : group.alerts
    );
  }, [groupedAlerts, isGroupCollapsed]);

  // Reset pagination when filters change
  useEffect(() => {
    setCurrentPage(1);
  }, [filters, groupingMode]);

  // Pagination calculations
  const totalAlerts = flatAlerts.length;
  const totalPages = Math.ceil(totalAlerts / ALERTS_PER_PAGE);
  const startIndex = (currentPage - 1) * ALERTS_PER_PAGE;
  const endIndex = startIndex + ALERTS_PER_PAGE;

  // Paginated alerts - slice the flat alerts for current page
  const paginatedAlerts = useMemo(() => {
    const alertsToShow = flatAlerts.slice(startIndex, endIndex);
    const alertIds = new Set(alertsToShow.map(a => a.id));

    // Filter groups to only show alerts on current page
    return groupedAlerts
      .map(group => ({
        ...group,
        alerts: group.alerts.filter(alert => alertIds.has(alert.id)),
        count: group.alerts.filter(alert => alertIds.has(alert.id)).length,
      }))
      .filter(group => group.alerts.length > 0);
  }, [groupedAlerts, flatAlerts, startIndex, endIndex]);

  const { focusedIndex } = useKeyboardNavigation(
    flatAlerts.length,
    {
      onMoveUp: () => {},
      onMoveDown: () => {},
      onSelect: () => {
        if (flatAlerts[focusedIndex]) {
          toggleAlertSelection(flatAlerts[focusedIndex].id);
        }
      },
      onExpand: () => {
        if (flatAlerts[focusedIndex]) {
          toggleAlertExpansion(flatAlerts[focusedIndex].id);
        }
      },
      onMarkAsRead: () => {
        if (flatAlerts[focusedIndex]) {
          handleMarkAsRead(flatAlerts[focusedIndex].id);
        }
      },
      onDismiss: () => {
        if (flatAlerts[focusedIndex]) {
          handleRemoveAlert(flatAlerts[focusedIndex].id);
        }
      },
      onSnooze: () => {
        if (flatAlerts[focusedIndex]) {
          handleSnoozeAlert(flatAlerts[focusedIndex].id, '1hr');
        }
      },
      onEscape: () => {
        setExpandedAlerts(new Set());
        setSelectedAlerts(new Set());
      },
      onSelectAll: () => {
        handleSelectAll();
      },
      onSearch: () => {},
    },
    true
  );

  const toggleAlertExpansion = useCallback((alertId: string) => {
    setExpandedAlerts(prev => {
      const next = new Set(prev);
      if (next.has(alertId)) {
        next.delete(alertId);
      } else {
        next.add(alertId);
      }
      return next;
    });
  }, []);

  const toggleAlertSelection = useCallback((alertId: string) => {
    setSelectedAlerts(prev => {
      const next = new Set(prev);
      if (next.has(alertId)) {
        next.delete(alertId);
      } else {
        next.add(alertId);
      }
      return next;
    });
  }, []);

  const handleMarkAsRead = useCallback((alertId: string) => {
    markAsRead(alertId);
    trackAcknowledgment(alertId).catch(err =>
      console.error('Failed to track acknowledgment:', err)
    );
  }, [markAsRead, trackAcknowledgment]);

  const handleRemoveAlert = useCallback((alertId: string) => {
    removeNotification(alertId);
    trackResolution(alertId).catch(err =>
      console.error('Failed to track resolution:', err)
    );
    setExpandedAlerts(prev => {
      const next = new Set(prev);
      next.delete(alertId);
      return next;
    });
    setSelectedAlerts(prev => {
      const next = new Set(prev);
      next.delete(alertId);
      return next;
    });
  }, [removeNotification, trackResolution]);

  const handleSnoozeAlert = useCallback((alertId: string, duration: '15min' | '1hr' | '4hr' | 'tomorrow' | number) => {
    snoozeAlert(alertId, duration);
  }, [snoozeAlert]);

  const handleUnsnoozeAlert = useCallback((alertId: string) => {
    unsnoozeAlert(alertId);
  }, [unsnoozeAlert]);

  const handleSelectAll = useCallback(() => {
    setSelectedAlerts(new Set(flatAlerts.map(a => a.id)));
    setShowBulkActions(true);
  }, [flatAlerts]);

  const handleDeselectAll = useCallback(() => {
    setSelectedAlerts(new Set());
    setShowBulkActions(false);
  }, []);

  const handleBulkMarkAsRead = useCallback(() => {
    const ids = Array.from(selectedAlerts);
    markMultipleAsRead(ids);
    ids.forEach(id =>
      trackAcknowledgment(id).catch(err =>
        console.error('Failed to track acknowledgment:', err)
      )
    );
    handleDeselectAll();
  }, [selectedAlerts, markMultipleAsRead, trackAcknowledgment, handleDeselectAll]);

  const handleBulkRemove = useCallback(() => {
    const ids = Array.from(selectedAlerts);
    removeMultiple(ids);
    ids.forEach(id =>
      trackResolution(id).catch(err =>
        console.error('Failed to track resolution:', err)
      )
    );
    handleDeselectAll();
  }, [selectedAlerts, removeMultiple, trackResolution, handleDeselectAll]);

  const handleBulkSnooze = useCallback((duration: '15min' | '1hr' | '4hr' | 'tomorrow' | number) => {
    const ids = Array.from(selectedAlerts);
    snoozeMultiple(ids, duration);
    handleDeselectAll();
  }, [selectedAlerts, snoozeMultiple, handleDeselectAll]);

  const activeAlerts = filteredNotifications.filter(a => a.status !== 'acknowledged' && !isAlertSnoozed(a.id));
  const urgentCount = activeAlerts.filter(a => a.severity === 'urgent').length;
  const highCount = activeAlerts.filter(a => a.severity === 'high').length;

  return (
    <Card className={className} variant="elevated" padding="none">
      <CardHeader padding="lg" divider>
        <div className="flex items-start sm:items-center justify-between w-full gap-4 flex-col sm:flex-row">
          <div className="flex items-center gap-3">
            <div
              className="p-2.5 rounded-xl shadow-sm flex-shrink-0"
              style={{ backgroundColor: 'var(--color-primary)15' }}
            >
              <Bell className="w-5 h-5" style={{ color: 'var(--color-primary)' }} />
            </div>
            <div>
              <h3 className="text-lg font-bold mb-0.5" style={{ color: 'var(--text-primary)' }}>
                {t('dashboard:alerts.title', 'Alertas')}
              </h3>
              <div className="flex items-center gap-2">
                {isConnected ? (
                  <Wifi className="w-3.5 h-3.5" style={{ color: 'var(--color-success)' }} />
                ) : (
                  <WifiOff className="w-3.5 h-3.5" style={{ color: 'var(--color-error)' }} />
                )}
                <span className="text-xs font-medium whitespace-nowrap" style={{ color: 'var(--text-secondary)' }}>
                  {isConnected
                    ? t('dashboard:alerts.live', 'En vivo')
                    : t('dashboard:alerts.offline', 'Desconectado')
                  }
                </span>
              </div>
            </div>
          </div>

          <div className="flex items-center gap-3 flex-wrap w-full sm:w-auto">
            {/* Alert count badges */}
            <div className="flex items-center gap-2">
              {urgentCount > 0 && (
                <SeverityBadge
                  severity="high"
                  count={urgentCount}
                  size="sm"
                />
              )}
              {highCount > 0 && (
                <SeverityBadge
                  severity="medium"
                  count={highCount}
                  size="sm"
                />
              )}
            </div>

            {/* Controls */}
            {showAnalytics && (
              <Button
                variant={showAnalyticsPanel ? 'primary' : 'ghost'}
                size="sm"
                onClick={() => setShowAnalyticsPanel(!showAnalyticsPanel)}
                className="h-9"
                title="Toggle analytics"
                aria-label="Toggle analytics panel"
              >
                <BarChart3 className="w-4 h-4" />
              </Button>
            )}

            {showGrouping && (
              <select
                value={groupingMode}
                onChange={(e) => setGroupingMode(e.target.value as GroupingMode)}
                className="px-3 py-2 text-sm font-medium border-2 border-[var(--border-primary)] rounded-lg bg-[var(--bg-primary)] text-[var(--text-primary)] focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)] focus:border-transparent transition-all cursor-pointer hover:border-[var(--color-primary)]"
                aria-label="Group alerts by"
              >
                <option value="time">⏰ Por tiempo</option>
                <option value="category">📁 Por categoría</option>
                <option value="similarity">🔗 Similares</option>
                <option value="none">📋 Sin agrupar</option>
              </select>
            )}
          </div>
        </div>
      </CardHeader>

      <CardBody padding="none">
        {showAnalyticsPanel && (
          <div className="p-4 border-b border-[var(--border-primary)]">
            <AlertTrends analytics={analytics} />
          </div>
        )}

        <div className="px-4 py-4 border-b border-[var(--border-primary)] bg-[var(--bg-secondary)]/30">
          <AlertFilters
            selectedSeverities={filters.severities}
            selectedCategories={filters.categories}
            selectedTimeRange={filters.timeRange}
            searchQuery={filters.search}
            showSnoozed={filters.showSnoozed}
            onToggleSeverity={toggleSeverity}
            onToggleCategory={toggleCategory}
            onSetTimeRange={setTimeRange}
            onSearchChange={setSearch}
            onToggleShowSnoozed={toggleShowSnoozed}
            onClearFilters={clearFilters}
            hasActiveFilters={hasActiveFilters}
            activeFilterCount={activeFilterCount}
          />
        </div>

        {selectedAlerts.size > 0 && (
          <div className="p-4 border-b border-[var(--border-primary)]">
            <AlertBulkActions
              selectedCount={selectedAlerts.size}
              totalCount={flatAlerts.length}
              onMarkAsRead={handleBulkMarkAsRead}
              onRemove={handleBulkRemove}
              onSnooze={handleBulkSnooze}
              onDeselectAll={handleDeselectAll}
              onSelectAll={handleSelectAll}
            />
          </div>
        )}

        {filteredNotifications.length === 0 ? (
          <div className="p-12 text-center">
            <div className="inline-flex items-center justify-center w-16 h-16 rounded-full bg-[var(--color-success)]/10 mb-4">
              <CheckCircle className="w-8 h-8" style={{ color: 'var(--color-success)' }} />
            </div>
            <h4 className="text-base font-semibold mb-2" style={{ color: 'var(--text-primary)' }}>
              {hasActiveFilters ? 'Sin resultados' : 'Todo despejado'}
            </h4>
            <p className="text-sm" style={{ color: 'var(--text-secondary)' }}>
              {hasActiveFilters
                ? 'No hay alertas que coincidan con los filtros seleccionados'
                : t('dashboard:alerts.no_alerts', 'No hay alertas activas en este momento')
              }
            </p>
          </div>
        ) : (
          <div className="space-y-3 p-4">
            {paginatedAlerts.map((group) => (
              <div key={group.id}>
                {(group.count > 1 || groupingMode !== 'none') && (
                  <div className="mb-3">
                    <AlertGroupHeader
                      group={group}
                      isCollapsed={isGroupCollapsed(group.id)}
                      onToggleCollapse={() => toggleGroupCollapse(group.id)}
                    />
                  </div>
                )}

                {!isGroupCollapsed(group.id) && (
                  <div className="space-y-3 ml-0">
                    {group.alerts.map((alert) => (
                      <AlertCard
                        key={alert.id}
                        alert={alert}
                        isExpanded={expandedAlerts.has(alert.id)}
                        isSelected={selectedAlerts.has(alert.id)}
                        isSnoozed={isAlertSnoozed(alert.id)}
                        snoozedUntil={snoozedAlerts.get(alert.id)?.until}
                        onToggleExpand={() => toggleAlertExpansion(alert.id)}
                        onToggleSelect={() => toggleAlertSelection(alert.id)}
                        onMarkAsRead={() => handleMarkAsRead(alert.id)}
                        onRemove={() => handleRemoveAlert(alert.id)}
                        onSnooze={(duration) => handleSnoozeAlert(alert.id, duration)}
                        onUnsnooze={() => handleUnsnoozeAlert(alert.id)}
                        showCheckbox={showBulkActions || selectedAlerts.size > 0}
                      />
                    ))}
                  </div>
                )}
              </div>
            ))}
          </div>
        )}

        {filteredNotifications.length > 0 && (
          <div
            className="px-4 py-3 border-t"
            style={{
              borderColor: 'var(--border-primary)',
              backgroundColor: 'var(--bg-secondary)/50',
            }}
          >
            <div className="flex flex-col gap-3">
              {/* Stats row */}
              <div className="flex items-center justify-between text-sm" style={{ color: 'var(--text-secondary)' }}>
                <span className="font-medium">
                  Mostrando <span className="font-bold text-[var(--text-primary)]">{startIndex + 1}-{Math.min(endIndex, totalAlerts)}</span> de <span className="font-bold text-[var(--text-primary)]">{totalAlerts}</span> alertas
                </span>
                <div className="flex items-center gap-4">
                  {stats.unread > 0 && (
                    <span className="flex items-center gap-1.5">
                      <span className="w-2 h-2 rounded-full bg-[var(--color-info)] animate-pulse" />
                      <span className="font-semibold text-[var(--text-primary)]">{stats.unread}</span> sin leer
                    </span>
                  )}
                  {stats.snoozed > 0 && (
                    <span className="flex items-center gap-1.5">
                      <Clock className="w-3.5 h-3.5" />
                      <span className="font-semibold text-[var(--text-primary)]">{stats.snoozed}</span> pospuestas
                    </span>
                  )}
                </div>
              </div>

              {/* Pagination controls */}
              {totalPages > 1 && (
                <div className="flex items-center justify-center gap-2">
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={() => setCurrentPage(prev => Math.max(1, prev - 1))}
                    disabled={currentPage === 1}
                    className="h-8 px-3"
                    aria-label="Previous page"
                  >
                    <ChevronLeft className="w-4 h-4" />
                  </Button>

                  <span className="text-sm font-medium px-3" style={{ color: 'var(--text-primary)' }}>
                    Página <span className="font-bold">{currentPage}</span> de <span className="font-bold">{totalPages}</span>
                  </span>

                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={() => setCurrentPage(prev => Math.min(totalPages, prev + 1))}
                    disabled={currentPage === totalPages}
                    className="h-8 px-3"
                    aria-label="Next page"
                  >
                    <ChevronRight className="w-4 h-4" />
                  </Button>
                </div>
              )}
            </div>
          </div>
        )}
      </CardBody>
    </Card>
  );
};

export default RealTimeAlerts;
