import React, { useState, useEffect, createContext, useContext } from 'react';
import { FiCheck, FiX, FiAlertTriangle, FiInfo, FiWifi, FiWifiOff } from 'react-icons/fi';
import './NotificationCenter.css';

// Context para notificações globais
const NotificationContext = createContext();

export const useNotification = () => {
  const context = useContext(NotificationContext);
  if (!context) {
    throw new Error('useNotification deve ser usado dentro de NotificationProvider');
  }
  return context;
};

// Provider de notificações
export const NotificationProvider = ({ children }) => {
  const [notifications, setNotifications] = useState([]);
  const [connectionStatus, setConnectionStatus] = useState('connected');

  // Adicionar notificação
  const addNotification = (message, type = 'info', duration = 5000) => {
    const id = Date.now() + Math.random();
    const notification = {
      id,
      message,
      type,
      timestamp: new Date(),
      duration
    };

    setNotifications(prev => [...prev, notification]);

    // Remover automaticamente após o tempo especificado
    if (duration > 0) {
      setTimeout(() => {
        removeNotification(id);
      }, duration);
    }

    return id;
  };

  // Remover notificação
  const removeNotification = (id) => {
    setNotifications(prev => prev.filter(n => n.id !== id));
  };

  // Notificações de conveniência
  const success = (message, duration) => addNotification(message, 'success', duration);
  const error = (message, duration) => addNotification(message, 'error', duration);
  const warning = (message, duration) => addNotification(message, 'warning', duration);
  const info = (message, duration) => addNotification(message, 'info', duration);

  // Monitorar conexão
  useEffect(() => {
    const checkConnection = async () => {
      try {
        const response = await fetch('/api/dashboard', { 
          method: 'GET',
          signal: AbortSignal.timeout(5000)
        });
        
        const newStatus = response.ok ? 'connected' : 'error';
        
        // Notificar mudanças de status
        if (connectionStatus !== newStatus) {
          if (newStatus === 'connected' && connectionStatus !== 'connected') {
            success('Conexão restaurada!', 3000);
          } else if (newStatus === 'error') {
            warning('Problemas de conexão detectados', 4000);
          }
        }
        
        setConnectionStatus(newStatus);
      } catch (error) {
        const newStatus = 'disconnected';
        
        if (connectionStatus !== newStatus) {
          error('Conexão perdida com o servidor', 5000);
        }
        
        setConnectionStatus(newStatus);
      }
    };

    // Verificar imediatamente
    checkConnection();

    // Verificar a cada 30 segundos
    const interval = setInterval(checkConnection, 30000);

    return () => clearInterval(interval);
  }, [connectionStatus]);

  const value = {
    notifications,
    connectionStatus,
    addNotification,
    removeNotification,
    success,
    error,
    warning,
    info
  };

  return (
    <NotificationContext.Provider value={value}>
      {children}
      <NotificationCenter />
    </NotificationContext.Provider>
  );
};

// Componente de notificações
const NotificationCenter = () => {
  const { notifications, removeNotification, connectionStatus } = useNotification();

  const getIcon = (type) => {
    switch (type) {
      case 'success': return <FiCheck />;
      case 'error': return <FiX />;
      case 'warning': return <FiAlertTriangle />;
      default: return <FiInfo />;
    }
  };

  const getConnectionIcon = () => {
    switch (connectionStatus) {
      case 'connected': return <FiWifi className="connection-icon connected" />;
      case 'disconnected': return <FiWifiOff className="connection-icon disconnected" />;
      case 'error': return <FiWifiOff className="connection-icon error" />;
      default: return <FiWifi className="connection-icon" />;
    }
  };

  const getConnectionText = () => {
    switch (connectionStatus) {
      case 'connected': return 'Online';
      case 'disconnected': return 'Offline';
      case 'error': return 'Instável';
      default: return 'Verificando...';
    }
  };

  return (
    <>
      {/* Status de conexão fixo */}
      <div className={`connection-indicator connection-${connectionStatus}`}>
        {getConnectionIcon()}
        <span className="connection-text">{getConnectionText()}</span>
      </div>

      {/* Container de notificações */}
      <div className="notification-container">
        {notifications.map((notification) => (
          <div
            key={notification.id}
            className={`notification notification-${notification.type}`}
            onClick={() => removeNotification(notification.id)}
          >
            <div className="notification-icon">
              {getIcon(notification.type)}
            </div>
            <div className="notification-content">
              <p className="notification-message">{notification.message}</p>
              <span className="notification-time">
                {notification.timestamp.toLocaleTimeString('pt-BR', {
                  hour: '2-digit',
                  minute: '2-digit'
                })}
              </span>
            </div>
            <button
              className="notification-close"
              onClick={(e) => {
                e.stopPropagation();
                removeNotification(notification.id);
              }}
            >
              <FiX />
            </button>
          </div>
        ))}
      </div>
    </>
  );
};

export default NotificationCenter;
