import React, { useState, useMemo, useCallback } from 'react';
import {
  Box,
  Card,
  CardContent,
  CardHeader,
  Typography,
  Grid,
  List,
  ListItem,
  ListItemText,
  ListItemIcon,
  Chip,
  LinearProgress,
  Paper,
  IconButton,
  Tooltip,
  Divider,
  Button,
  Alert,
  CircularProgress,
  Select,
  MenuItem,
  FormControl,
  InputLabel,
  Skeleton,
  Fade,
  Grow,
  useTheme,
  alpha,
  Badge
} from '@mui/material';
import {
  Visibility as VisibilityIcon,
  People as PeopleIcon,
  Today as TodayIcon,
  DateRange as DateRangeIcon,
  Language as LanguageIcon,
  Computer as ComputerIcon,
  Link as LinkIcon,
  Refresh as RefreshIcon,
  Download as DownloadIcon,
  Clear as ClearIcon,
  Timeline as TimelineIcon,
  Cookie as CookieIcon,
  CheckCircle as CheckCircleIcon,
  Cancel as CancelIcon,
  Error as ErrorIcon,
  Warning as WarningIcon,
  TrendingUp as TrendingUpIcon,
  TrendingDown as TrendingDownIcon,
  AccessTime as AccessTimeIcon,
  FilterList as FilterListIcon,
  MoreVert as MoreVertIcon,
  AutoGraph as AutoGraphIcon
} from '@mui/icons-material';

import useAnalytics from '../hooks/useAnalytics';

const AnalyticsWidget = () => {
  const theme = useTheme();
  const {
    metrics,
    refreshMetrics,
    clearLocalAnalytics,
    exportMetrics,
    loadMetrics
  } = useAnalytics();


  const [selectedPeriod, setSelectedPeriod] = useState('week');
  const [showExportPanel, setShowExportPanel] = useState(false);
  const [exportType, setExportType] = useState('visits');
  const [exportFormat, setExportFormat] = useState('json');

  // Colores personalizados con tonos azules modernos
  const customColors = {
    primary: '#1976d2',
    secondary: '#42a5f5',
    tertiary: '#0d47a1',
    accent: '#2196f3',
    gradient1: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
    gradient2: 'linear-gradient(135deg, #1e3c72 0%, #2a5298 100%)',
    gradient3: 'linear-gradient(135deg, #0575e6 0%, #021b79 100%)',
    gradient4: 'linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)',
    gradient5: 'linear-gradient(135deg, #43e97b 0%, #38f9d7 100%)',
    success: '#4caf50',
    warning: '#ff9800',
    error: '#f44336'
  };

  const formatDate = useCallback((dateString) => {
    return new Date(dateString).toLocaleString('es-ES', {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    });
  }, []);

  const formatNumber = useCallback((num) => {
    if (num >= 1000000) return `${(num / 1000000).toFixed(1)}M`;
    if (num >= 1000) return `${(num / 1000).toFixed(1)}K`;
    return num.toLocaleString();
  }, []);

  const getConsentStatus = useMemo(() => {
    if (!metrics?.cookieConsent) {
      return { status: 'No definido', color: 'default', icon: CookieIcon };
    }
    if (metrics.cookieConsent.accepted) {
      return { status: 'Aceptadas', color: 'success', icon: CheckCircleIcon };
    }
    return { status: 'Rechazadas', color: 'error', icon: CancelIcon };
  }, [metrics?.cookieConsent]);



  const MetricCard = ({ title, value, icon: Icon, gradient, trend, subtitle }) => (
    <Card
      sx={{
        height: '100%',
        background: gradient,
        color: 'white',
        transition: 'all 0.3s ease',
        cursor: 'pointer',
        '&:hover': {
          transform: 'translateY(-5px)',
          boxShadow: theme.shadows[10]
        }
      }}
    >
      <CardContent sx={{ position: 'relative', overflow: 'hidden' }}>
        <Icon sx={{
          position: 'absolute',
          right: -10,
          top: -10,
          fontSize: 100,
          opacity: 0.1
        }} />

        <Box sx={{ display: 'flex', alignItems: 'center', mb: 1 }}>
          <Icon sx={{ fontSize: 24, mr: 1, opacity: 0.9 }} />
          <Typography variant="caption" sx={{
            textTransform: 'uppercase',
            letterSpacing: '1.5px',
            fontWeight: 500
          }}>
            {title}
          </Typography>
        </Box>

        <Typography variant="h3" sx={{ fontWeight: 'bold', mb: 1 }}>
          {formatNumber(value)}
        </Typography>

        {trend !== undefined && (
          <Box sx={{ display: 'flex', alignItems: 'center', mt: 1 }}>
            {trend > 0 ? (
              <TrendingUpIcon sx={{ fontSize: 20, mr: 0.5 }} />
            ) : (
              <TrendingDownIcon sx={{ fontSize: 20, mr: 0.5 }} />
            )}
            <Typography variant="body2" sx={{ opacity: 0.9 }}>
              {trend > 0 ? '+' : ''}{trend}% vs período anterior
            </Typography>
          </Box>
        )}

        {subtitle && (
          <Typography variant="caption" sx={{ opacity: 0.8, display: 'block', mt: 1 }}>
            {subtitle}
          </Typography>
        )}
      </CardContent>
    </Card>
  );

  const DataCard = ({ title, icon: Icon, color, children, action }) => (
    <Card
      sx={{
        height: '100%',
        borderTop: `3px solid ${color}`,
        transition: 'all 0.3s ease',
        '&:hover': {
          boxShadow: theme.shadows[8]
        }
      }}
    >
      <CardHeader
        avatar={
          <Box sx={{
            p: 1,
            borderRadius: 2,
            backgroundColor: alpha(color, 0.1),
            display: 'flex'
          }}>
            <Icon sx={{ color: color, fontSize: 24 }} />
          </Box>
        }
        title={
          <Typography variant="h6" sx={{ fontWeight: 600, color: '#2c3e50' }}>
            {title}
          </Typography>
        }
        action={action}
        sx={{ pb: 0 }}
      />
      <CardContent>
        {children}
      </CardContent>
    </Card>
  );

  return (
    <Box sx={{ p: { xs: 2, md: 3 } }}>
      {/* Header mejorado */}
      <Paper
        elevation={0}
        sx={{
          p: 3,
          mb: 3,
          background: customColors.gradient2,
          color: 'white',
          borderRadius: 2
        }}
      >
        <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 2 }}>
          <Box>
            <Typography variant="h4" sx={{ fontWeight: 700, mb: 1, display: 'flex', alignItems: 'center' }}>
              <AutoGraphIcon sx={{ mr: 2, fontSize: 40 }} />
              Panel de Analytics
            </Typography>
            <Typography variant="body1" sx={{ opacity: 0.9 }}>
              Monitoreo en tiempo real del rendimiento de tu sitio
            </Typography>
          </Box>

          <Box sx={{ display: 'flex', gap: 1, flexWrap: 'wrap' }}>
            <FormControl size="small" sx={{ minWidth: 120 }}>
              <Select
                value={selectedPeriod}
                onChange={(e) => setSelectedPeriod(e.target.value)}
                sx={{
                  backgroundColor: 'rgba(255,255,255,0.1)',
                  color: 'white',
                  '& .MuiSelect-icon': { color: 'white' },
                  '&:hover': { backgroundColor: 'rgba(255,255,255,0.2)' }
                }}
              >
                <MenuItem value="today">Hoy</MenuItem>
                <MenuItem value="week">Esta Semana</MenuItem>
                <MenuItem value="month">Este Mes</MenuItem>
                <MenuItem value="year">Este Año</MenuItem>
              </Select>
            </FormControl>

            <Button
              variant="contained"
              startIcon={<DownloadIcon />}
              onClick={() => setShowExportPanel(!showExportPanel)}
              sx={{
                backgroundColor: 'rgba(255,255,255,0.2)',
                '&:hover': { backgroundColor: 'rgba(255,255,255,0.3)' }
              }}
            >
              Exportar
            </Button>

            <Tooltip title="Actualizar métricas">
              <IconButton
                onClick={refreshMetrics}
                sx={{
                  color: 'white',
                  backgroundColor: 'rgba(255,255,255,0.1)',
                  '&:hover': { backgroundColor: 'rgba(255,255,255,0.2)' }
                }}
                disabled={metrics.loading}
              >
                {metrics.loading ? <CircularProgress size={24} color="inherit" /> : <RefreshIcon />}
              </IconButton>
            </Tooltip>
          </Box>
        </Box>
      </Paper>

      {/* Panel de exportación colapsable */}
      {showExportPanel && (
        <Grow in={showExportPanel}>
          <Paper sx={{ p: 2, mb: 3, backgroundColor: alpha(customColors.primary, 0.05) }}>
            <Grid container spacing={2} alignItems="center">
              <Grid item xs={12} sm={3}>
                <FormControl fullWidth size="small">
                  <InputLabel>Tipo de Datos</InputLabel>
                  <Select
                    value={exportType}
                    label="Tipo de Datos"
                    onChange={(e) => setExportType(e.target.value)}
                  >
                    <MenuItem value="visits">Visitas</MenuItem>
                    <MenuItem value="events">Eventos</MenuItem>
                    <MenuItem value="consent">Consentimientos</MenuItem>
                    <MenuItem value="all">Todos los datos</MenuItem>
                  </Select>
                </FormControl>
              </Grid>
              <Grid item xs={12} sm={3}>
                <FormControl fullWidth size="small">
                  <InputLabel>Formato</InputLabel>
                  <Select
                    value={exportFormat}
                    label="Formato"
                    onChange={(e) => setExportFormat(e.target.value)}
                  >
                    <MenuItem value="json">JSON</MenuItem>
                    <MenuItem value="csv">CSV</MenuItem>
                    <MenuItem value="excel">Excel</MenuItem>
                    <MenuItem value="pdf">PDF</MenuItem>
                  </Select>
                </FormControl>
              </Grid>
              <Grid item xs={12} sm={3}>
                <Button
                  variant="contained"
                  onClick={() => exportMetrics(exportType, exportFormat)}
                  startIcon={<DownloadIcon />}
                  fullWidth
                  sx={{
                    background: customColors.gradient2,
                    '&:hover': { background: customColors.gradient3 }
                  }}
                >
                  Descargar
                </Button>
              </Grid>
              <Grid item xs={12} sm={3}>
                <Button
                  variant="outlined"
                  onClick={() => setShowExportPanel(false)}
                  fullWidth
                >
                  Cancelar
                </Button>
              </Grid>
            </Grid>
          </Paper>
        </Grow>
      )}

      {/* Cards de métricas principales con animación */}
      <Grid container spacing={3} sx={{ mb: 3 }}>
        <Grid item xs={12} sm={6} md={3}>
          <Fade in timeout={500}>
            <Box>
              <MetricCard
                title="Total Visitas"
                value={metrics?.totalVisits || 0}
                icon={VisibilityIcon}
                gradient={customColors.gradient2}
                trend={metrics?.growth?.visits}
              />
            </Box>
          </Fade>
        </Grid>

        <Grid item xs={12} sm={6} md={3}>
          <Fade in timeout={700}>
            <Box>
              <MetricCard
                title="Visitantes Únicos"
                value={metrics?.uniqueVisitors || 0}
                icon={PeopleIcon}
                gradient={customColors.gradient3}
                trend={metrics?.growth?.visitors}
              />
            </Box>
          </Fade>
        </Grid>

        <Grid item xs={12} sm={6} md={3}>
          <Fade in timeout={900}>
            <Box>
              <MetricCard
                title="Visitas Hoy"
                value={metrics?.todayVisits || 0}
                icon={TodayIcon}
                gradient={customColors.gradient4}
                subtitle="Actualizado hace 5 min"
              />
            </Box>
          </Fade>
        </Grid>

        <Grid item xs={12} sm={6} md={3}>
          <Fade in timeout={1100}>
            <Box>
              <MetricCard
                title="Esta Semana"
                value={metrics?.thisWeekVisits || 0}
                icon={DateRangeIcon}
                gradient={customColors.gradient5}
                subtitle={`Promedio: ${Math.floor((metrics?.thisWeekVisits || 0) / 7)}/día`}
              />
            </Box>
          </Fade>
        </Grid>
      </Grid>

      {/* Métricas adicionales */}
      <Grid container spacing={3} sx={{ mb: 3 }}>
        <Grid item xs={12} sm={4}>
          <Paper
            sx={{
              p: 2,
              textAlign: 'center',
              borderLeft: `4px solid ${customColors.warning}`,
              transition: 'all 0.3s',
              '&:hover': { boxShadow: 4 }
            }}
          >
            <Typography variant="subtitle2" color="text.secondary" gutterBottom>
              Tasa de Rebote
            </Typography>
            <Typography variant="h4" sx={{ color: customColors.warning, fontWeight: 'bold' }}>
              {metrics?.bounceRate || 0}%
            </Typography>
          </Paper>
        </Grid>

        <Grid item xs={12} sm={4}>
          <Paper
            sx={{
              p: 2,
              textAlign: 'center',
              borderLeft: `4px solid ${customColors.success}`,
              transition: 'all 0.3s',
              '&:hover': { boxShadow: 4 }
            }}
          >
            <Typography variant="subtitle2" color="text.secondary" gutterBottom>
              Duración Promedio
            </Typography>
            <Typography variant="h4" sx={{ color: customColors.success, fontWeight: 'bold' }}>
              {metrics?.averageSessionDuration || '0m 0s'}
            </Typography>
          </Paper>
        </Grid>

        <Grid item xs={12} sm={4}>
          <Paper
            sx={{
              p: 2,
              textAlign: 'center',
              borderLeft: `4px solid ${customColors.primary}`,
              transition: 'all 0.3s',
              '&:hover': { boxShadow: 4 }
            }}
          >
            <Typography variant="subtitle2" color="text.secondary" gutterBottom>
              Estado de Cookies
            </Typography>
            <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 1 }}>
              <getConsentStatus.icon sx={{ color: customColors.primary }} />
              <Typography variant="h5" sx={{ color: customColors.primary, fontWeight: 'bold' }}>
                {getConsentStatus.status}
              </Typography>
            </Box>
          </Paper>
        </Grid>
      </Grid>

      {/* Contenido principal */}
      <Grid container spacing={3}>
        {/* Páginas más visitadas */}
        <Grid item xs={12} lg={6}>
          <DataCard
            title="Páginas Más Visitadas"
            icon={LanguageIcon}
            color={customColors.primary}
            action={
              <Chip
                label={`${metrics?.topPages?.length || 0} páginas`}
                size="small"
                sx={{ backgroundColor: alpha(customColors.primary, 0.1) }}
              />
            }
          >
            {metrics.loading ? (
              <Box>
                {[1, 2, 3].map((i) => (
                  <Skeleton key={i} height={60} sx={{ mb: 1 }} />
                ))}
              </Box>
            ) : (
              <List sx={{ p: 0 }}>
                {metrics?.topPages?.map((page, index) => (
                  <ListItem
                    key={index}
                    sx={{
                      py: 1.5,
                      px: 0,
                      '&:hover': { backgroundColor: alpha(customColors.primary, 0.05) },
                      borderRadius: 1,
                      transition: 'all 0.2s'
                    }}
                  >
                    <ListItemIcon>
                      <Badge
                        badgeContent={index + 1}
                        color={index < 3 ? "primary" : "default"}
                        sx={{ '& .MuiBadge-badge': { fontWeight: 'bold' } }}
                      >
                        <Box sx={{ width: 24, height: 24 }} />
                      </Badge>
                    </ListItemIcon>
                    <ListItemText
                      primary={
                        <Typography variant="body1" sx={{ fontWeight: 500 }}>
                          {page.page === '/' ? 'Página principal' : page.page}
                        </Typography>
                      }
                      secondary={`${formatNumber(page.views)} visitas`}
                    />
                    <Box sx={{ minWidth: 100 }}>
                      <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                        <LinearProgress
                          variant="determinate"
                          value={metrics.topPages[0]?.views ? (page.views / metrics.pageViews) * 100 : 0}
                          sx={{
                            height: 8,
                            borderRadius: 4,
                            flexGrow: 1,
                            backgroundColor: alpha(customColors.primary, 0.1),
                            '& .MuiLinearProgress-bar': {
                              background: customColors.gradient2
                            }
                          }}
                        />
                        <Typography variant="caption" color="text.secondary" sx={{ minWidth: 40 }}>
                          {metrics.totalVisits > 0 ? ((page.views / metrics.pageViews) * 100).toFixed(1) : 0}%
                        </Typography>
                      </Box>
                    </Box>
                  </ListItem>
                ))}
              </List>
            )}
          </DataCard>
        </Grid>

        {/* Fuentes de tráfico */}
        <Grid item xs={12} lg={6}>
          <DataCard
            title="Fuentes de Tráfico"
            icon={LinkIcon}
            color={customColors.success}
            action={
              <IconButton size="small">
                <FilterListIcon />
              </IconButton>
            }
          >
            {metrics.loading ? (
              <Box>
                {[1, 2, 3].map((i) => (
                  <Skeleton key={i} height={60} sx={{ mb: 1 }} />
                ))}
              </Box>
            ) : (
              <List sx={{ p: 0 }}>
                {metrics?.topReferrers?.map((referrer, index) => (
                  <ListItem
                    key={index}
                    sx={{
                      py: 1.5,
                      px: 0,
                      '&:hover': { backgroundColor: alpha(customColors.success, 0.05) },
                      borderRadius: 1,
                      transition: 'all 0.2s'
                    }}
                  >
                    <ListItemIcon>
                      <Badge
                        badgeContent={index + 1}
                        color={index < 3 ? "success" : "default"}
                        sx={{ '& .MuiBadge-badge': { fontWeight: 'bold' } }}
                      >
                        <Box sx={{ width: 24, height: 24 }} />
                      </Badge>
                    </ListItemIcon>
                    <ListItemText
                      primary={
                        <Typography variant="body1" sx={{ fontWeight: 500 }}>
                          {referrer.referrer}
                        </Typography>
                      }
                      secondary={`${formatNumber(referrer.visits)} visitas`}
                    />
                    <Box sx={{ minWidth: 100 }}>
                      <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                        <LinearProgress
                          variant="determinate"
                          value={(referrer.visits / metrics.topReferrers[0].visits) * 100}
                          sx={{
                            height: 8,
                            borderRadius: 4,
                            flexGrow: 1,
                            backgroundColor: alpha(customColors.success, 0.1),
                            '& .MuiLinearProgress-bar': {
                              backgroundColor: customColors.success
                            }
                          }}
                        />
                        <Typography variant="caption" color="text.secondary" sx={{ minWidth: 40 }}>
                          {((referrer.visits / metrics.pageViews) * 100).toFixed(1)}%
                        </Typography>
                      </Box>
                    </Box>
                  </ListItem>
                ))}
              </List>
            )}
          </DataCard>
        </Grid>

        {/* Navegadores */}
        <Grid item xs={12} lg={6}>
          <DataCard
            title="Navegadores"
            icon={ComputerIcon}
            color={customColors.warning}
          >
            {metrics.loading ? (
              <Box>
                {[1, 2, 3].map((i) => (
                  <Skeleton key={i} height={40} sx={{ mb: 2 }} />
                ))}
              </Box>
            ) : (
              <Box>
                {metrics?.browserStats?.map((browser, index) => (
                  <Box key={index} sx={{ mb: 2.5 }}>
                    <Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 1 }}>
                      <Typography variant="body2" sx={{ fontWeight: 500 }}>
                        {browser.browser}
                      </Typography>
                      <Typography variant="body2" color="text.secondary">
                        {formatNumber(browser.count)} ({((browser.count / metrics.pageViews) * 100).toFixed(1)}%)
                      </Typography>
                    </Box>
                    <LinearProgress
                      variant="determinate"
                      value={(browser.count / metrics.browserStats[0].count) * 100}
                      sx={{
                        height: 10,
                        borderRadius: 5,
                        backgroundColor: alpha(customColors.warning, 0.1),
                        '& .MuiLinearProgress-bar': {
                          backgroundColor: customColors.warning,
                          borderRadius: 5
                        }
                      }}
                    />
                  </Box>
                ))}
              </Box>
            )}
          </DataCard>
        </Grid>

        {/* Historial reciente mejorado */}
        <Grid item xs={12} lg={6}>
          <DataCard
            title="Actividad Reciente"
            icon={AccessTimeIcon}
            color={customColors.tertiary}
            action={
              <Box sx={{ display: 'flex', gap: 1 }}>
                <Chip
                  label="En vivo"
                  size="small"
                  sx={{
                    backgroundColor: customColors.success,
                    color: 'white',
                    '& .MuiChip-label': { px: 1 }
                  }}
                />
                <IconButton size="small">
                  <MoreVertIcon />
                </IconButton>
              </Box>
            }
          >
            {metrics.loading ? (
              <Box>
                {[1, 2, 3].map((i) => (
                  <Skeleton key={i} height={70} sx={{ mb: 1 }} />
                ))}
              </Box>
            ) : (
              <Box sx={{ maxHeight: 350, overflowY: 'auto' }}>
                {metrics?.visitHistory?.slice(0, 5).map((visit, index) => (
                  <Paper
                    key={index}
                    elevation={0}
                    sx={{
                      p: 2,
                      mb: 1.5,
                      backgroundColor: alpha(customColors.primary, 0.03),
                      borderLeft: `3px solid ${customColors.primary}`,
                      transition: 'all 0.2s',
                      '&:hover': {
                        backgroundColor: alpha(customColors.primary, 0.08),
                        transform: 'translateX(5px)'
                      }
                    }}
                  >
                    <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'start' }}>
                      <Box>
                        <Typography variant="body1" sx={{ fontWeight: 500, color: customColors.tertiary }}>
                          {visit.path === '/' ? 'Página principal' : visit.path}
                        </Typography>
                        <Typography variant="caption" color="text.secondary" sx={{ display: 'block', mt: 0.5 }}>
                          {formatDate(visit.timestamp)}
                        </Typography>
                        <Typography variant="caption" color="text.secondary" sx={{ display: 'block', mt: 0.5 }}>
                          {visit.ip}
                        </Typography>
                      </Box>
                      <Chip
                        label={visit.referrer === 'direct' ? 'Directo' : visit.referrer || visit.referrer === 'http://localhost:3000/' ? 'Local' : visit.referrer}
                        size="small"
                        variant="outlined"
                        sx={{
                          borderColor: alpha(customColors.primary, 0.3),
                          fontSize: '0.7rem'
                        }}
                      />
                    </Box>
                  </Paper>
                ))}
              </Box>
            )}
          </DataCard>
        </Grid>
      </Grid>
    </Box>
  );
};

export default AnalyticsWidget;