import React, { useState, useEffect } from 'react';
import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Typography,
  Switch,
  FormControlLabel,
  Button,
  Box,
  Divider,
  IconButton,
  List,
  ListItem,
  ListItemText,
  ListItemSecondaryAction,
  Alert
} from '@mui/material';
import {
  Close as CloseIcon,
  Cookie as CookieIcon,
  Security as SecurityIcon,
  Analytics as AnalyticsIcon,
  Speed as SpeedIcon
} from '@mui/icons-material';

const CookieSettings = ({ open, onClose, onSave }) => {
  const [settings, setSettings] = useState(() => {
    // Cargar configuración guardada
    const savedSettings = localStorage.getItem('sempreg-cookie-settings');
    if (savedSettings) {
      const parsed = JSON.parse(savedSettings);
      return { ...{
        essential: true, // Siempre activadas
        analytics: false,
        performance: false,
        marketing: false
      }, ...parsed };
    }
    return {
      essential: true, // Siempre activadas
      analytics: false,
      performance: false,
      marketing: false
    };
  });

  const handleToggle = (type) => {
    if (type === 'essential') return; // No se puede desactivar
    
    setSettings(prev => ({
      ...prev,
      [type]: !prev[type]
    }));
  };

  const handleSave = () => {
    localStorage.setItem('sempreg-cookie-settings', JSON.stringify(settings));
    localStorage.setItem('sempreg-cookie-consent', JSON.stringify({
      accepted: true,
      timestamp: new Date().toISOString(),
      version: '1.0',
      settings
    }));
    
    onSave && onSave(settings);
    onClose();
  };

  const handleAcceptAll = () => {
    const allAccepted = {
      essential: true,
      analytics: true,
      performance: true,
      marketing: true
    };
    
    setSettings(allAccepted);
    localStorage.setItem('sempreg-cookie-settings', JSON.stringify(allAccepted));
    localStorage.setItem('sempreg-cookie-consent', JSON.stringify({
      accepted: true,
      timestamp: new Date().toISOString(),
      version: '1.0',
      settings: allAccepted
    }));
    
    onSave && onSave(allAccepted);
    onClose();
  };

  const handleRejectAll = () => {
    const onlyEssential = {
      essential: true,
      analytics: false,
      performance: false,
      marketing: false
    };
    
    setSettings(onlyEssential);
    localStorage.setItem('sempreg-cookie-settings', JSON.stringify(onlyEssential));
    localStorage.setItem('sempreg-cookie-consent', JSON.stringify({
      accepted: false,
      timestamp: new Date().toISOString(),
      version: '1.0',
      settings: onlyEssential
    }));
    
    onSave && onSave(onlyEssential);
    onClose();
  };

  const cookieTypes = [
    {
      type: 'essential',
      title: 'Cookies Esenciales',
      description: 'Necesarias para el funcionamiento básico del sitio web. No se pueden desactivar.',
      icon: SecurityIcon,
      color: '#4caf50',
      enabled: settings.essential,
      required: true
    },
    {
      type: 'analytics',
      title: 'Cookies Analíticas',
      description: 'Nos ayudan a entender cómo los visitantes interactúan con nuestro sitio web.',
      icon: AnalyticsIcon,
      color: '#2196f3',
      enabled: settings.analytics,
      required: false
    },
    {
      type: 'performance',
      title: 'Cookies de Rendimiento',
      description: 'Mejoran la velocidad y el rendimiento del sitio web.',
      icon: SpeedIcon,
      color: '#ff9800',
      enabled: settings.performance,
      required: false
    },
    {
      type: 'marketing',
      title: 'Cookies de Marketing',
      description: 'Se utilizan para mostrar anuncios relevantes y medir la efectividad de las campañas.',
      icon: CookieIcon,
      color: '#9c27b0',
      enabled: settings.marketing,
      required: false
    }
  ];

  return (
    <Dialog
      open={open}
      onClose={onClose}
      maxWidth="md"
      fullWidth
      PaperProps={{
        sx: { borderRadius: 2 }
      }}
    >
      <DialogTitle sx={{ 
        display: 'flex', 
        alignItems: 'center', 
        justifyContent: 'space-between',
        backgroundColor: '#f5f5f5',
        borderBottom: '1px solid #e0e0e0'
      }}>
        <Box sx={{ display: 'flex', alignItems: 'center' }}>
          <CookieIcon sx={{ mr: 1, color: '#2f70aa' }} />
          <Typography variant="h6" sx={{ fontWeight: 600 }}>
            Configuración de Cookies
          </Typography>
        </Box>
        <IconButton onClick={onClose} size="small">
          <CloseIcon />
        </IconButton>
      </DialogTitle>

      <DialogContent sx={{ p: 3 }}>
        <Alert severity="info" sx={{ mb: 3 }}>
          <Typography variant="body2">
            Utilizamos cookies para mejorar tu experiencia de navegación. Puedes personalizar 
            qué tipos de cookies aceptas usando los controles a continuación.
          </Typography>
        </Alert>

        <List>
          {cookieTypes.map((cookie, index) => {
            const IconComponent = cookie.icon;
            return (
              <React.Fragment key={cookie.type}>
                <ListItem sx={{ py: 2, px: 0 }}>
                  <Box sx={{ display: 'flex', alignItems: 'flex-start', width: '100%' }}>
                    <Box sx={{ mr: 2, mt: 0.5 }}>
                      <IconComponent sx={{ color: cookie.color, fontSize: 24 }} />
                    </Box>
                    <Box sx={{ flexGrow: 1 }}>
                      <Typography variant="subtitle1" sx={{ fontWeight: 600, mb: 0.5 }}>
                        {cookie.title}
                        {cookie.required && (
                          <Typography component="span" variant="caption" sx={{ 
                            ml: 1, 
                            color: 'error.main',
                            fontWeight: 'normal'
                          }}>
                            (Requeridas)
                          </Typography>
                        )}
                      </Typography>
                      <Typography variant="body2" color="text.secondary">
                        {cookie.description}
                      </Typography>
                    </Box>
                    <ListItemSecondaryAction>
                      <FormControlLabel
                        control={
                          <Switch
                            checked={cookie.enabled}
                            onChange={() => handleToggle(cookie.type)}
                            disabled={cookie.required}
                            color="primary"
                          />
                        }
                        label=""
                        sx={{ m: 0 }}
                      />
                    </ListItemSecondaryAction>
                  </Box>
                </ListItem>
                {index < cookieTypes.length - 1 && <Divider />}
              </React.Fragment>
            );
          })}
        </List>

        <Box sx={{ mt: 3, p: 2, backgroundColor: '#f8f9fa', borderRadius: 1 }}>
          <Typography variant="body2" color="text.secondary">
            <strong>Nota:</strong> Puedes cambiar estas configuraciones en cualquier momento. 
            Algunas funciones del sitio web pueden no estar disponibles si desactivas ciertas cookies.
          </Typography>
        </Box>
      </DialogContent>

      <DialogActions sx={{ p: 3, pt: 0 }}>
        <Box sx={{ display: 'flex', gap: 1, width: '100%', flexDirection: { xs: 'column', sm: 'row' } }}>
          <Button
            variant="outlined"
            onClick={handleRejectAll}
            sx={{ 
              flex: { sm: 1 },
              borderColor: '#999',
              color: '#666',
              '&:hover': { borderColor: '#666', backgroundColor: '#f5f5f5' }
            }}
          >
            Rechazar Todo
          </Button>
          <Button
            variant="outlined"
            onClick={handleSave}
            sx={{ 
              flex: { sm: 1 },
              borderColor: '#2f70aa',
              color: '#2f70aa',
              '&:hover': { borderColor: '#245d8f', backgroundColor: '#f0f7ff' }
            }}
          >
            Guardar Configuración
          </Button>
          <Button
            variant="contained"
            onClick={handleAcceptAll}
            sx={{
              flex: { sm: 1 },
              backgroundColor: '#4caf50',
              '&:hover': { backgroundColor: '#45a049' }
            }}
          >
            Aceptar Todo
          </Button>
        </Box>
      </DialogActions>
    </Dialog>
  );
};

export default CookieSettings;
