import React, { useState, useEffect } from 'react';
import {
  Box,
  Paper,
  Typography,
  Button,
  IconButton,
  Collapse,
  Fade,
  useTheme,
  useMediaQuery
} from '@mui/material';
import {
  Close as CloseIcon,
  Cookie as CookieIcon,
  Settings as SettingsIcon,
  CheckCircle as CheckCircleIcon
} from '@mui/icons-material';
import CookieSettings from './CookieSettings';
import analyticsService from '@/services/analyticsService';
import { getCookieConsent, saveCookieConsent, hasConsentFor, migrateCookiePreferences } from '../utils/cookies';

const CookieBanner = () => {
  const [showBanner, setShowBanner] = useState(false);
  const [showDetails, setShowDetails] = useState(false);
  const [showSettings, setShowSettings] = useState(false);
  const [accepted, setAccepted] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down('md'));

  useEffect(() => {
    let mounted = true;
    
    const initializeCookieConsent = async () => {
      if (!mounted) return;
      
      try {
        // Migrar preferencias existentes (solo una vez)
        migrateCookiePreferences();
        
        // Verificar consentimiento existente
        const cookieConsent = getCookieConsent();
        
        if (!cookieConsent && mounted) {
          // No hay consentimiento -> mostrar banner
          const timer = setTimeout(() => {
            if (mounted) {
              setShowBanner(true);
            }
          }, 1500); // Aumentar delay para evitar flash
          
          return () => clearTimeout(timer);
        } else if (cookieConsent && mounted) {
          // Ya hay consentimiento -> inicializar analytics si está habilitado
                    
          // Actualizar el estado del servicio de analytics
          if (cookieConsent.accepted && hasConsentFor('analytics')) {
            // Asegurar que el servicio tenga el consentimiento actualizado
            analyticsService.cookieConsent = {
              accepted: true,
              settings: {
                essential: true,
                analytics: true,
                performance: hasConsentFor('performance') || false,
                marketing: hasConsentFor('marketing') || false
              },
              timestamp: cookieConsent.timestamp || new Date().toISOString()
            };
            
            // Inicializar tracking automáticamente
            try {
              await analyticsService.trackPageView({
                initialLoad: true,
                consentStatus: 'previously_accepted'
              });
                          } catch (error) {
              console.error('❌ Error inicializando analytics:', error);
            }
          } else {
                      }
        }
      } catch (error) {
        console.error('❌ Error inicializando consentimiento de cookies:', error);
        // En caso de error, mostrar el banner por seguridad
        if (mounted) {
          setShowBanner(true);
        }
      }
    };

    initializeCookieConsent();
    
    return () => {
      mounted = false;
    };
  }, []);

  const handleAccept = async () => {
    if (isLoading) return;
    setIsLoading(true);
    
    try {
      // Configuración completa (todas las cookies)
      const settings = {
        essential: true,
        analytics: true,
        performance: true,
        marketing: false // Mantener marketing como false por defecto
      };
      
      // Guardar consentimiento usando la utilidad de cookies
      saveCookieConsent(true, 'all');
      
      // Actualizar el servicio de analytics PRIMERO
      analyticsService.cookieConsent = {
        accepted: true,
        settings,
        timestamp: new Date().toISOString()
      };
      
      // Registrar consentimiento en el backend
      await analyticsService.recordCookieConsent(true, settings);
      
      // Ahora inicializar el tracking
      await analyticsService.trackPageView({
        consentAction: 'accept_all',
        timestamp: new Date().toISOString()
      });
      
      setAccepted(true);
            
      // Cerrar banner después de confirmar
      setTimeout(() => {
        setShowBanner(false);
      }, 2000);
      
    } catch (error) {
      console.error('❌ Error procesando aceptación:', error);
      // Aún así guardar localmente y cerrar
      saveCookieConsent(true, 'all');
      setAccepted(true);
      setTimeout(() => setShowBanner(false), 2000);
    } finally {
      setIsLoading(false);
    }
  };

  const handleReject = async () => {
    if (isLoading) return;
    setIsLoading(true);
    
    try {
      // Solo cookies esenciales
      const settings = {
        essential: true,
        analytics: false,
        performance: false,
        marketing: false
      };
      
      // Guardar rechazo
      saveCookieConsent(false, 'essential');
      
      // Actualizar servicio de analytics
      analyticsService.cookieConsent = {
        accepted: false,
        settings,
        timestamp: new Date().toISOString()
      };
      
      // Registrar rechazo (esto debería ser permitido incluso sin consentimiento analytics)
      await analyticsService.recordCookieConsent(false, settings);
      
            setShowBanner(false);
      
    } catch (error) {
      console.error('❌ Error procesando rechazo:', error);
      // Guardar localmente de todos modos
      saveCookieConsent(false, 'essential');
      setShowBanner(false);
    } finally {
      setIsLoading(false);
    }
  };

  const handleCustomize = () => {
    setShowSettings(true);
  };

  const handleSettingsClose = async (customSettings) => {
    if (customSettings) {
      setIsLoading(true);
      
      try {
        // Determinar tipo de consentimiento
        const hasAnalytics = customSettings.analytics || false;
        const hasPerformance = customSettings.performance || false;
        const consentType = hasAnalytics ? 'analytics' : 'essential';
        
        // Guardar configuración personalizada
        saveCookieConsent(true, consentType);
        
        // Actualizar servicio de analytics
        analyticsService.cookieConsent = {
          accepted: true,
          settings: {
            essential: true,
            ...customSettings
          },
          timestamp: new Date().toISOString()
        };
        
        // Registrar consentimiento personalizado
        await analyticsService.recordCookieConsent(true, {
          essential: true,
          ...customSettings
        });
        
        // Inicializar tracking solo si analytics están habilitadas
        if (hasAnalytics) {
          await analyticsService.trackPageView({
            consentAction: 'customize',
            settings: customSettings
          });
        }
        
        setAccepted(true);
                
        setTimeout(() => {
          setShowBanner(false);
        }, 2000);
        
      } catch (error) {
        console.error('❌ Error guardando configuración personalizada:', error);
        // Fallback
        const consentType = customSettings.analytics ? 'analytics' : 'essential';
        saveCookieConsent(true, consentType);
        setAccepted(true);
        setTimeout(() => setShowBanner(false), 2000);
      } finally {
        setIsLoading(false);
      }
    }
    
    setShowSettings(false);
  };

  const handleClose = () => {
    // Solo permitir cerrar si ya hay algún consentimiento previo
    const existingConsent = getCookieConsent();
    if (existingConsent) {
      setShowBanner(false);
    }
  };

  const toggleDetails = () => {
    setShowDetails(!showDetails);
  };

  if (!showBanner) return null;

  return (
    <>
      <Fade in={showBanner}>
        <Box
          sx={{
            position: 'fixed',
            bottom: 0,
            left: 0,
            right: 0,
            zIndex: 9999,
            p: { xs: 2, sm: 3 }
          }}
        >
          <Paper
            elevation={8}
            sx={{
              maxWidth: '1200px',
              mx: 'auto',
              background: accepted 
                ? 'linear-gradient(135deg, #4caf50 0%, #45a049 100%)'
                : 'linear-gradient(135deg, #1976d2 0%, #1565c0 100%)',
              color: 'white',
              borderRadius: 3,
              overflow: 'hidden',
              position: 'relative',
              border: '2px solid rgba(255,255,255,0.1)'
            }}
          >
            {/* Header */}
            <Box sx={{ p: 3, pb: showDetails ? 2 : 3 }}>
              <Box sx={{ display: 'flex', alignItems: 'flex-start', gap: 2 }}>
                <CookieIcon sx={{ fontSize: 32, mt: 0.5, opacity: 0.9 }} />
                
                <Box sx={{ flex: 1, minWidth: 0 }}>
                  <Typography 
                    variant="h6" 
                    sx={{ 
                      fontWeight: 600, 
                      mb: 1,
                      display: 'flex',
                      alignItems: 'center',
                      gap: 1
                    }}
                  >
                    {accepted ? (
                      <>
                        <CheckCircleIcon sx={{ fontSize: 24 }} />
                        ¡Configuración Guardada!
                      </>
                    ) : (
                      'Política de Cookies'
                    )}
                  </Typography>
                  
                  <Typography variant="body2" sx={{ opacity: 0.9, lineHeight: 1.6 }}>
                    {accepted ? (
                      'Hemos guardado tu preferencia de cookies. Puedes cambiarla en cualquier momento desde el botón flotante.'
                    ) : (
                      'Utilizamos cookies esenciales para el funcionamiento del sitio y cookies analíticas para mejorar tu experiencia. '
                    )}
                    {!accepted && (
                      <Button 
                        color="inherit" 
                        size="small" 
                        onClick={toggleDetails}
                        sx={{ 
                          textDecoration: 'underline', 
                          p: 0, 
                          minWidth: 'auto',
                          fontWeight: 'inherit'
                        }}
                      >
                        {showDetails ? 'Ver menos' : 'Más información'}
                      </Button>
                    )}
                  </Typography>
                </Box>

                {/* Solo mostrar X si hay consentimiento previo */}
                {getCookieConsent() && (
                  <IconButton 
                    onClick={handleClose}
                    sx={{ 
                      color: 'white',
                      '&:hover': { 
                        backgroundColor: 'rgba(255,255,255,0.1)' 
                      }
                    }}
                    size="small"
                  >
                    <CloseIcon />
                  </IconButton>
                )}
              </Box>

              {/* Botones de acción */}
              {!accepted && (
                <Box 
                  sx={{ 
                    display: 'flex', 
                    gap: 1.5, 
                    mt: 3,
                    flexDirection: { xs: 'column', sm: 'row' },
                    alignItems: { xs: 'stretch', sm: 'center' }
                  }}
                >
                  <Button
                    onClick={handleAccept}
                    variant="contained"
                    disabled={isLoading}
                    sx={{
                      backgroundColor: 'rgba(255,255,255,0.2)',
                      color: 'white',
                      fontWeight: 600,
                      px: 3,
                      py: 1,
                      '&:hover': {
                        backgroundColor: 'rgba(255,255,255,0.3)'
                      },
                      '&:disabled': {
                        backgroundColor: 'rgba(255,255,255,0.1)',
                        color: 'rgba(255,255,255,0.6)'
                      },
                      flex: { xs: 1, sm: 'none' }
                    }}
                  >
                    {isLoading ? 'Procesando...' : 'Aceptar Todas'}
                  </Button>
                  
                  <Button
                    onClick={handleCustomize}
                    variant="outlined"
                    startIcon={<SettingsIcon />}
                    disabled={isLoading}
                    sx={{
                      borderColor: 'rgba(255,255,255,0.3)',
                      color: 'white',
                      fontWeight: 500,
                      px: 3,
                      py: 1,
                      '&:hover': {
                        borderColor: 'rgba(255,255,255,0.5)',
                        backgroundColor: 'rgba(255,255,255,0.1)'
                      },
                      '&:disabled': {
                        borderColor: 'rgba(255,255,255,0.2)',
                        color: 'rgba(255,255,255,0.6)'
                      },
                      flex: { xs: 1, sm: 'none' }
                    }}
                  >
                    Personalizar
                  </Button>
                  
                  <Button
                    onClick={handleReject}
                    variant="text"
                    disabled={isLoading}
                    sx={{
                      color: 'rgba(255,255,255,0.8)',
                      fontWeight: 500,
                      px: 3,
                      py: 1,
                      '&:hover': {
                        backgroundColor: 'rgba(255,255,255,0.1)',
                        color: 'white'
                      },
                      '&:disabled': {
                        color: 'rgba(255,255,255,0.5)'
                      },
                      flex: { xs: 1, sm: 'none' }
                    }}
                  >
                    Rechazar
                  </Button>
                </Box>
              )}
            </Box>

            {/* Detalles expandibles */}
            <Collapse in={showDetails}>
              <Box sx={{ px: 3, pb: 3, pt: 0 }}>
                <Box sx={{ 
                  backgroundColor: 'rgba(255,255,255,0.1)', 
                  borderRadius: 2, 
                  p: 2.5,
                  border: '1px solid rgba(255,255,255,0.1)'
                }}>
                  <Typography variant="subtitle2" sx={{ fontWeight: 600, mb: 2 }}>
                    Tipos de Cookies que Utilizamos:
                  </Typography>
                  
                  <Box sx={{ display: 'flex', flexDirection: 'column', gap: 1.5 }}>
                    <Box>
                      <Typography variant="body2" sx={{ fontWeight: 600, mb: 0.5 }}>
                        🔒 Cookies Esenciales (Obligatorias)
                      </Typography>
                      <Typography variant="body2" sx={{ opacity: 0.9, fontSize: '0.85rem' }}>
                        Necesarias para el funcionamiento básico del sitio web.
                      </Typography>
                    </Box>
                    
                    <Box>
                      <Typography variant="body2" sx={{ fontWeight: 600, mb: 0.5 }}>
                        📊 Cookies Analíticas (Opcionales)
                      </Typography>
                      <Typography variant="body2" sx={{ opacity: 0.9, fontSize: '0.85rem' }}>
                        Nos ayudan a entender cómo interactúas con nuestro sitio para mejorarlo.
                      </Typography>
                    </Box>
                    
                    <Box>
                      <Typography variant="body2" sx={{ fontWeight: 600, mb: 0.5 }}>
                        ⚡ Cookies de Rendimiento (Opcionales)
                      </Typography>
                      <Typography variant="body2" sx={{ opacity: 0.9, fontSize: '0.85rem' }}>
                        Mejoran la velocidad y funcionalidad del sitio web.
                      </Typography>
                    </Box>
                  </Box>
                </Box>
              </Box>
            </Collapse>
          </Paper>
        </Box>
      </Fade>

      {/* Modal de configuración personalizada */}
      <CookieSettings 
        open={showSettings} 
        onClose={handleSettingsClose}
      />
    </>
  );
};

export default CookieBanner;
