import React, { useState, useMemo, useRef, useEffect, useCallback } from 'react';
import {
  Box,
  Paper,
  Typography,
  Button,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogContentText,
  DialogActions,
  List,
  ListItem,
  ListItemIcon,
  ListItemText,
  useTheme,
  alpha,
  Tooltip,
  IconButton,
  Alert,
  AlertTitle,
  Stack,
  Chip,
  Divider,
} from '@mui/material';
import InfoIcon from '@mui/icons-material/Info';
import CheckCircleIcon from '@mui/icons-material/CheckCircle';
import WarningIcon from '@mui/icons-material/Warning';
import ThermostatIcon from '@mui/icons-material/Thermostat';
import CalendarMonthIcon from '@mui/icons-material/CalendarMonth';
import ScienceIcon from '@mui/icons-material/Science';
import BugReportIcon from '@mui/icons-material/BugReport';
import TrendingUpIcon from '@mui/icons-material/TrendingUp';
import CalculateIcon from '@mui/icons-material/Calculate';
import FunctionsIcon from '@mui/icons-material/Functions';
import PercentIcon from '@mui/icons-material/Percent';
import PetsIcon from '@mui/icons-material/Pets';
import CompareIcon from '@mui/icons-material/Compare';
import {
  LineChart,
  Line,
  XAxis,
  YAxis,
  CartesianGrid,
  ResponsiveContainer,
  ReferenceLine,
  Label,
  Dot,
  Tooltip as RechartsTooltip,
  Legend,
  ReferenceArea
} from 'recharts';
import { generarPrediccionVarroa, prepararDatosRecharts, CONSTANTES_VARROA } from '../../models/varroa';
import { Tratamiento } from '../../models/varroa/types';

interface VarroaPredictiveChartProps {
  numAcaros: number;
  numAbejas: number;
  fechaMuestra: Date;
  tratamientos: Tratamiento[];
}

const CustomTooltip = ({ active, payload, label, tratamientos }: any) => {
  if (active && payload && payload.length) {
    const fecha = new Date(label);
    const formattedDate = fecha.toLocaleDateString();

    // Check if this date corresponds to a treatment
    const tratamientoEnFecha = tratamientos?.find((t: Tratamiento) => {
      const tratDate = new Date(t.fecha);
      return tratDate.toDateString() === fecha.toDateString();
    });

    return (
      <Box sx={{ bgcolor: 'background.paper', p: 2, border: '1px solid #ccc', borderRadius: 1, boxShadow: 1 }}>
        <Typography variant="subtitle2" sx={{ mb: 1 }}>
          Date: {formattedDate}
        </Typography>
        
        {payload.map((entry: any, index: number) => (
          <Typography key={`item-${index}`} variant="body2" sx={{ color: entry.color }}>
            {entry.name}: {entry.value.toLocaleString(undefined, { maximumFractionDigits: 2 })}
          </Typography>
        ))}
        
        {tratamientoEnFecha && (
          <Box sx={{ mt: 1, pt: 1, borderTop: '1px dashed #ccc' }}>
            <Typography variant="body2" sx={{ fontWeight: 'bold', color: '#F2994A' }}>
              Treatment applied: {tratamientoEnFecha.nombre} ({tratamientoEnFecha.eficiencia}% effectiveness)
            </Typography>
          </Box>
        )}
      </Box>
    );
  }

  return null;
};

const VarroaPredictiveChart: React.FC<VarroaPredictiveChartProps> = ({
  numAcaros,
  numAbejas,
  fechaMuestra,
  tratamientos
}) => {
  const theme = useTheme();
  const [openInfoDialog, setOpenInfoDialog] = useState(false);

  const handleOpenInfoDialog = () => {
    setOpenInfoDialog(true);
  };

  const handleCloseInfoDialog = () => {
    setOpenInfoDialog(false);
  };

  // State to control which treatments are selected in the comparative chart
  const [tratamientosSeleccionados, setTratamientosSeleccionados] = useState<Record<string, boolean>>({});

  // Initialize selected treatments when treatments change
  useEffect(() => {
    const initialState: Record<string, boolean> = {};
    tratamientos.forEach(tratamiento => {
      // Use the name or a unique representation as key
      const key = tratamiento.nombre || `tratamiento-${JSON.stringify(tratamiento.fecha)}-${tratamiento.eficiencia}`;
      initialState[key] = true; // By default, all treatments are selected
    });
    setTratamientosSeleccionados(initialState);
  }, [tratamientos]);

  // Function to change the selection state of a treatment
  const toggleTratamiento = (key: string) => {
    setTratamientosSeleccionados(prev => ({
      ...prev,
      [key]: !prev[key]
    }));
  };

  // Generate prediction
  const prediccion = useMemo(() => {
    return generarPrediccionVarroa({
      numAcaros,
      numAbejas,
      fechaMuestra,
      tratamientos
    });
  }, [numAcaros, numAbejas, fechaMuestra, tratamientos]);

  // Generate prediction without treatments and individual predictions for each treatment
  const prediccionesComparativas = useMemo(() => {
    // Prediction without treatments
    const sinTratamiento = generarPrediccionVarroa({
      numAcaros,
      numAbejas,
      fechaMuestra,
      tratamientos: []
    });

    // Individual predictions for each treatment
    const prediccionesPorTratamiento = tratamientos.map(tratamiento => {
      // Create a copy of the treatment to ensure each prediction is independent
      const tratamientoIndividual = { 
        ...tratamiento,
        // Ensure the date is a copy
        fecha: new Date(tratamiento.fecha.getTime())
      };
      
      return {
        tratamiento: tratamientoIndividual,
        prediccion: generarPrediccionVarroa({
          numAcaros,
          numAbejas,
          fechaMuestra,
          // Apply ONLY this individual treatment
          tratamientos: [tratamientoIndividual]
        })
      };
    });

    return {
      sinTratamiento,
      prediccionesPorTratamiento
    };
  }, [numAcaros, numAbejas, fechaMuestra, tratamientos]);

  // Prepare data for the chart
  const datosGrafica = useMemo(() => {
    const datos = prepararDatosRecharts({
      fechas: prediccion.resultadosDiarios.map(r => r.fecha),
      poblacionAcaros: prediccion.resultadosDiarios.map(r => r.poblacionAcaros),
      caidaNatural: prediccion.resultadosDiarios.map(r => r.caidaNatural),
      infestacionAbejas: prediccion.resultadosDiarios.map(r => r.infestacionAbejas),
      umbralesCriticos: {
        poblacion: 0,
        caidaNatural: CONSTANTES_VARROA.UMBRAL_CAIDA_NATURAL_VERANO,
        infestacionAbejas: CONSTANTES_VARROA.UMBRAL_INFESTACION_CRITICO
      },
      tratamientos
    });

    // Filter to show only one point every 7 days (to avoid overloading the chart)
    return datos.filter((_, index) => index % 7 === 0);
  }, [prediccion, tratamientos]);

  // Prepare data for the comparative chart
  const datosGraficaComparativa = useMemo(() => {
    // Data without treatment
    const datosSinTratamiento = prepararDatosRecharts({
      fechas: prediccionesComparativas.sinTratamiento.resultadosDiarios.map(r => r.fecha),
      poblacionAcaros: prediccionesComparativas.sinTratamiento.resultadosDiarios.map(r => r.poblacionAcaros),
      caidaNatural: prediccionesComparativas.sinTratamiento.resultadosDiarios.map(r => r.caidaNatural),
      infestacionAbejas: prediccionesComparativas.sinTratamiento.resultadosDiarios.map(r => r.infestacionAbejas),
      umbralesCriticos: {
        poblacion: 0,
        caidaNatural: CONSTANTES_VARROA.UMBRAL_CAIDA_NATURAL_VERANO,
        infestacionAbejas: CONSTANTES_VARROA.UMBRAL_INFESTACION_CRITICO
      },
      tratamientos: []
    });

    // Filter to show only one point every 7 days
    return datosSinTratamiento.filter((_, index) => index % 7 === 0);
  }, [prediccionesComparativas]);

  // Prepare data for each individual treatment
  const datosPorTratamiento = useMemo(() => {
    return prediccionesComparativas.prediccionesPorTratamiento.map((item, index) => {
      // Ensure each treatment has different data
      const datosTratamiento = prepararDatosRecharts({
        fechas: item.prediccion.resultadosDiarios.map(r => r.fecha),
        // Apply the treatment's efficiency to reduce the population
        poblacionAcaros: item.prediccion.resultadosDiarios.map(r => {
          const eficiencia = item.tratamiento.eficiencia / 100;
          return r.poblacionAcaros * (1 - eficiencia);
        }),
        caidaNatural: item.prediccion.resultadosDiarios.map(r => r.caidaNatural),
        infestacionAbejas: item.prediccion.resultadosDiarios.map(r => r.infestacionAbejas),
        umbralesCriticos: {
          poblacion: 0,
          caidaNatural: CONSTANTES_VARROA.UMBRAL_CAIDA_NATURAL_VERANO,
          infestacionAbejas: CONSTANTES_VARROA.UMBRAL_INFESTACION_CRITICO
        },
        tratamientos: []  // Do not include treatments here to avoid confusion
      }).filter((_, i) => i % 7 === 0);

      // Generate a unique key for this treatment
      const key = item.tratamiento.nombre || `tratamiento-${JSON.stringify(item.tratamiento.fecha)}-${item.tratamiento.eficiencia}`;

      return {
        tratamiento: item.tratamiento,
        datos: datosTratamiento,
        key
      };
    });
  }, [prediccionesComparativas]);

  // Function to select all treatments
  const seleccionarTodos = useCallback(() => {
    const newState: Record<string, boolean> = {};
    datosPorTratamiento.forEach(item => {
      newState[item.key] = true;
    });
    setTratamientosSeleccionados(newState);
  }, [datosPorTratamiento]);

  // Function to deselect all treatments
  const deseleccionarTodos = useCallback(() => {
    const newState: Record<string, boolean> = {};
    datosPorTratamiento.forEach(item => {
      newState[item.key] = false;
    });
    setTratamientosSeleccionados(newState);
  }, [datosPorTratamiento]);

  // Generate colors for each treatment
  const coloresTratamientos = useMemo(() => {
    const coloresBase = [
      '#27AE60', // Green
      '#2F80ED', // Blue
      '#9B51E0', // Purple
      '#F2994A', // Orange
      '#EB5757', // Red
      '#BB6BD9', // Violet
      '#56CCF2', // Sky blue
      '#219653', // Dark green
      '#F2C94C'  // Yellow
    ];

    return tratamientos.reduce((acc, tratamiento, index) => {
      acc[tratamiento.nombre || `Treatment ${index + 1}`] = coloresBase[index % coloresBase.length];
      return acc;
    }, {} as Record<string, string>);
  }, [tratamientos]);

  // Find treatment points
  const puntosTratamiento = useMemo(() => {
    return tratamientos.map(tratamiento => {
      const index = datosGrafica.findIndex(
        punto => punto.fecha.getTime() >= tratamiento.fecha.getTime()
      );
      return index >= 0 ? index : -1;
    }).filter(index => index !== -1);
  }, [datosGrafica, tratamientos]);

  // Calculate additional statistics
  const estadisticas = {
    maximaPoblacion: Math.round(prediccion.estadisticas.maximaPoblacion),
    fechaMaxima: prediccion.estadisticas.fechaMaxima.toLocaleDateString(),
    promedioInfestacion: prediccion.estadisticas.promedioInfestacion.toFixed(2),
    infestacionFinal: Number(prediccion.resultadosDiarios[prediccion.resultadosDiarios.length - 1].infestacionAbejas.toFixed(2)),
    acarosFinales: prediccion.resultadosDiarios[prediccion.resultadosDiarios.length - 1].poblacionAcaros,
    caidaNatural: prediccion.resultadosDiarios[prediccion.resultadosDiarios.length - 1].caidaNatural.toFixed(1)
  };

  const infestacionInicial = (numAcaros / numAbejas) * 100;

  // Generate recommendation based on the results
  const recomendacion = useMemo(() => {
    if (estadisticas.infestacionFinal >= 3) {
      return "The projection indicates that your colony will reach a critical infestation level. It is recommended to apply an effective treatment as soon as possible and monitor the colony frequently to evaluate its effectiveness.";
    } else if (estadisticas.infestacionFinal >= 1.5) {
      return "The projected infestation level is approaching the critical threshold. Consider planning a preventive treatment before the mite population increases significantly.";
    } else {
      return "The projected infestation level is under control. Continue with regular monitoring and maintain good beekeeping practices.";
    }
  }, [estadisticas.infestacionFinal]);

  return (
    <Box>
      <Paper elevation={3} sx={{ p: 3, mb: 3 }}>
        <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
          <Typography variant="h5" gutterBottom sx={{ display: 'flex', alignItems: 'center', gap: 1, color: theme.palette.primary.main, fontWeight: 'bold' }}>
            <BugReportIcon /> Varroa Predictive Model
          </Typography>
          <IconButton 
            color="primary" 
            onClick={handleOpenInfoDialog}
            size="large"
            sx={{ 
              border: `1px solid ${theme.palette.primary.main}`,
              borderRadius: '50%',
              '&:hover': {
                backgroundColor: theme.palette.action.hover
              }
            }}
          >
            <InfoIcon />
          </IconButton>
        </Box>

        <Typography variant="body1" paragraph>
          This scientific model predicts the growth of the Varroa destructor mite population in your colony over time, based on current data and planned treatments.
        </Typography>

        <Alert severity="info" sx={{ mb: 3 }}>
          <AlertTitle>Important Information</AlertTitle>
          <Typography variant="body2">
            This predictive model is based on scientific research and provides an estimate of Varroa population growth. Results may vary depending on local conditions, colony management, and environmental factors.
          </Typography>
        </Alert>

        <Box sx={{ mt: 3, mb: 4, p: 2, bgcolor: theme.palette.action.selected, borderRadius: 1 }}>
          <Typography variant="subtitle1" gutterBottom sx={{ fontWeight: 'bold', color: theme.palette.info.main }}>
            Initial Data:
          </Typography>
          <Stack direction={{ xs: 'column', sm: 'row' }} spacing={2} sx={{ mb: 2 }}>
            <Tooltip title="Estimated number of Varroa mites in the colony at the beginning of the projection period">
              <Chip 
                icon={<BugReportIcon />} 
                label={`Initial mites: ${numAcaros.toLocaleString()}`} 
                color="primary" 
                variant="outlined" 
              />
            </Tooltip>
            <Tooltip title="Percentage of adult bees infested with mites at the beginning of the projection period">
              <Chip 
                icon={<PercentIcon />} 
                label={`Initial infestation: ${infestacionInicial.toFixed(1)}%`} 
                color={infestacionInicial >= 3 ? "error" : "success"} 
                variant="outlined" 
              />
            </Tooltip>
            <Tooltip title="Estimated number of adult bees in the colony">
              <Chip 
                icon={<PetsIcon />} 
                label={`Bee population: ${numAbejas.toLocaleString()}`} 
                color="primary" 
                variant="outlined" 
              />
            </Tooltip>
          </Stack>
          
          <Typography variant="subtitle1" gutterBottom sx={{ fontWeight: 'bold', color: theme.palette.info.main, mt: 2 }}>
            90-Day Projection:
          </Typography>
          <Stack direction={{ xs: 'column', sm: 'row' }} spacing={2}>
            <Tooltip title="Total mite population estimated for day 90 of the projection">
              <Chip 
                icon={<BugReportIcon />} 
                label={`Projected mites: ${estadisticas.acarosFinales.toFixed(0)}`} 
                color={estadisticas.acarosFinales > numAcaros ? "error" : "primary"} 
                variant="outlined" 
              />
            </Tooltip>
            <Tooltip title="Percentage of adult bees infested with mites at the end of the projection period">
              <Chip 
                icon={<WarningIcon />} 
                label={`Projected infestation: ${estadisticas.infestacionFinal.toFixed(1)}%`} 
                color={Number(estadisticas.infestacionFinal) >= 3 ? "error" : "success"} 
                variant="outlined" 
              />
            </Tooltip>
            <Tooltip title="Daily average of naturally falling mites during the projection period">
              <Chip 
                icon={<ThermostatIcon />} 
                label={`Daily natural fall: ${estadisticas.caidaNatural} mites/day`} 
                color={Number(estadisticas.caidaNatural) >= CONSTANTES_VARROA.UMBRAL_CAIDA_NATURAL_VERANO ? "error" : "primary"} 
                variant="outlined" 
              />
            </Tooltip>
          </Stack>
        </Box>

        {estadisticas.infestacionFinal >= 3 && (
          <Alert severity="warning" sx={{ mb: 3 }}>
            <AlertTitle>Warning! Critical Infestation Level</AlertTitle>
            <Typography variant="body2">
              The projection indicates that your colony will reach a critical infestation level of {estadisticas.infestacionFinal}% in the next 90 days, exceeding the recommended threshold of 3%. Additional treatments and frequent colony monitoring are recommended.
            </Typography>
          </Alert>
        )}

        <Typography variant="subtitle1" gutterBottom sx={{ mt: 3, fontWeight: 'bold', display: 'flex', alignItems: 'center', gap: 1 }}>
          <TrendingUpIcon color="primary" /> Mite Population and Infestation Rate
        </Typography>
        <Typography variant="body2" paragraph>
          The graph shows the evolution of the mite population (red line) and the infestation percentage (blue line) over the next 90 days. Highlighted points indicate treatment moments.
        </Typography>
        <ResponsiveContainer width="100%" height={400}>
          <LineChart data={datosGrafica} margin={{ top: 5, right: 30, left: 20, bottom: 5 }}>
            <CartesianGrid strokeDasharray="3 3" />
            <XAxis 
              dataKey="etiqueta" 
              interval={4} 
              angle={-45}
              textAnchor="end"
              height={70}
            />
            <YAxis 
              yAxisId="left"
              orientation="left"
              label={{ value: 'Mite population', angle: -90, position: 'insideLeft' }}
            />
            <YAxis 
              yAxisId="right"
              orientation="right"
              label={{ value: 'Infestation (%)', angle: -90, position: 'insideRight' }}
            />
            <RechartsTooltip content={<CustomTooltip tratamientos={tratamientos} />} />
            <Legend />
            
            {/* Mite population line */}
            <Line 
              type="monotone" 
              dataKey="poblacionAcaros" 
              stroke={CONSTANTES_VARROA.COLORES.POBLACION_ACAROS} 
              yAxisId="left"
              name="Mite population"
              dot={(props) => {
                // Check if it's a treatment point
                const { cx, cy, payload, index } = props;
                const fecha = new Date(payload.fecha);
                
                const esTratamiento = tratamientos.some(t => {
                  const tratDate = new Date(t.fecha);
                  return tratDate.toDateString() === fecha.toDateString();
                });
                
                if (esTratamiento) {
                  return (
                    <circle 
                      cx={cx} 
                      cy={cy} 
                      r={6} 
                      fill={CONSTANTES_VARROA.COLORES.TRATAMIENTO} 
                      stroke="white" 
                      strokeWidth={2}
                    />
                  );
                }
                
                // Invisible point for other cases
                return (
                  <circle 
                    cx={cx} 
                    cy={cy} 
                    r={0} 
                    fill="transparent"
                  />
                );
              }}
            />
            
            {/* Infestation line */}
            <Line 
              type="monotone" 
              dataKey="infestacionAbejas" 
              stroke={CONSTANTES_VARROA.COLORES.INFESTACION} 
              yAxisId="right"
              name="Infestation (%)"
              dot={(props) => {
                const { cx, cy, payload, index, points } = props;
                const fecha = new Date(payload.fecha);
                
                // Check if it's a treatment point
                const esTratamiento = tratamientos.some(t => {
                  const tratDate = new Date(t.fecha);
                  return tratDate.toDateString() === fecha.toDateString();
                });
                
                if (esTratamiento) {
                  return (
                    <circle 
                      cx={cx} 
                      cy={cy} 
                      r={6} 
                      fill={CONSTANTES_VARROA.COLORES.TRATAMIENTO} 
                      stroke="white" 
                      strokeWidth={2}
                    />
                  );
                }
                
                // Check if this point is in post-treatment period (7-14 days after)
                const esPostTratamiento = tratamientos.some(t => {
                  const tratDate = new Date(t.fecha);
                  const diffTime = fecha.getTime() - tratDate.getTime();
                  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
                  return diffDays > 0 && diffDays <= 14;
                });
                
                // Check if there's an infestation peak
                if (esPostTratamiento && index > 0) {
                  try {
                    // Safely access data from the previous point
                    const prevInfestacion = datosGrafica[index-1]?.infestacionAbejas || 0;
                    const currentInfestacion = payload.infestacionAbejas || 0;
                    
                    if (prevInfestacion > 0 && currentInfestacion > 0 && 
                        currentInfestacion > prevInfestacion * 1.2) {
                      return (
                        <g>
                          <circle cx={cx} cy={cy} r={5} fill="#ff5722" stroke="white" strokeWidth={1} />
                          <text x={cx} y={cy - 10} textAnchor="middle" fill="#ff5722" fontSize={10} fontWeight="bold">
                            !
                          </text>
                        </g>
                      );
                    }
                  } catch (error) {
                    // If there's an error, we simply continue without showing annotation
                    console.error("Error checking infestation peak:", error);
                  }
                }
                
                // Invisible point for other cases
                return (
                  <circle 
                    cx={cx} 
                    cy={cy} 
                    r={0} 
                    fill="transparent"
                  />
                );
              }}
            />
            
            {/* Critical threshold line */}
            <ReferenceLine 
              yAxisId="right"
              y={CONSTANTES_VARROA.UMBRAL_INFESTACION_CRITICO} 
              stroke={CONSTANTES_VARROA.COLORES.UMBRAL_CRITICO} 
              strokeDasharray="3 3"
            >
              <Label 
                value="Critical threshold (3%)" 
                position="insideBottomRight"
                fill={CONSTANTES_VARROA.COLORES.UMBRAL_CRITICO}
              />
            </ReferenceLine>
          </LineChart>
        </ResponsiveContainer>

        <Box sx={{ mt: 4 }}>
          <Typography variant="subtitle1" gutterBottom sx={{ mt: 3, fontWeight: 'bold', display: 'flex', alignItems: 'center', gap: 1 }}>
            <TrendingUpIcon color="primary" /> Daily Natural Fall
          </Typography>
          <Typography variant="body2" paragraph>
            This graph shows the estimated mites that fall naturally per day, a key indicator for monitoring infestation. The dotted red line indicates the critical threshold of 10 mites/day in summer.
          </Typography>
          <ResponsiveContainer width="100%" height={200}>
            <LineChart data={datosGrafica} margin={{ top: 5, right: 30, left: 20, bottom: 5 }}>
              <CartesianGrid strokeDasharray="3 3" />
              <XAxis 
                dataKey="etiqueta" 
                interval={4} 
                angle={-45}
                textAnchor="end"
                height={70}
              />
              <YAxis 
                label={{ value: 'Mites/day', angle: -90, position: 'insideLeft' }}
              />
              <RechartsTooltip content={<CustomTooltip tratamientos={tratamientos} />} />
              <Legend />
              
              {/* Natural fall line */}
              <Line 
                type="monotone" 
                dataKey="caidaNatural" 
                name="Natural fall (mites/day)" 
                stroke={CONSTANTES_VARROA.COLORES.CAIDA_NATURAL} 
                dot={false}
                strokeWidth={2}
              />
              
              {/* Critical threshold line */}
              <ReferenceLine 
                y={CONSTANTES_VARROA.UMBRAL_CAIDA_NATURAL_VERANO} 
                stroke={CONSTANTES_VARROA.COLORES.UMBRAL_CRITICO} 
                strokeDasharray="3 3"
              >
                <Label 
                  value="Critical threshold (10/day)" 
                  position="insideBottomRight"
                  fill={CONSTANTES_VARROA.COLORES.UMBRAL_CRITICO}
                />
              </ReferenceLine>
            </LineChart>
          </ResponsiveContainer>
        </Box>

        {/* New comparative treatments chart */}
        <Box sx={{ mt: 4 }}>
          <Typography variant="h6" color="primary" gutterBottom sx={{ mt: 2, display: 'flex', alignItems: 'center', gap: 1 }}>
            <CompareIcon /> Treatment Comparison
          </Typography>
          <Typography variant="body2" paragraph>
            This graph shows a comparison of Varroa population growth without treatment (red line) versus growth with each of the selected treatments.
          </Typography>

          {/* Controls to select/deselect treatments */}
          <Box sx={{ mb: 2, display: 'flex', flexDirection: 'column', gap: 1 }}>
            <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <Typography variant="subtitle2" sx={{ fontWeight: 'medium' }}>
                Select treatments to display:
              </Typography>
              <Box sx={{ display: 'flex', gap: 1 }}>
                <Button 
                  size="small" 
                  variant="outlined" 
                  onClick={seleccionarTodos}
                  sx={{ fontSize: '0.7rem', py: 0.5 }}
                >
                  Select all
                </Button>
                <Button 
                  size="small" 
                  variant="outlined" 
                  onClick={deseleccionarTodos}
                  sx={{ fontSize: '0.7rem', py: 0.5 }}
                >
                  Deselect all
                </Button>
              </Box>
            </Box>
            <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 1 }}>
              {datosPorTratamiento.map((item) => {
                const nombreTratamiento = item.tratamiento.nombre || `Treatment`;
                const color = coloresTratamientos[nombreTratamiento];
                const isSelected = tratamientosSeleccionados[item.key] || false;
                
                return (
                  <Chip
                    key={item.key}
                    label={`${nombreTratamiento} (${item.tratamiento.eficiencia}%)`}
                    sx={{
                      backgroundColor: isSelected ? color : 'transparent',
                      color: isSelected ? 'white' : 'inherit',
                      borderColor: color,
                      border: '1px solid',
                      '&:hover': {
                        backgroundColor: isSelected ? color : `${color}33`,
                      }
                    }}
                    onClick={() => toggleTratamiento(item.key)}
                    variant={isSelected ? "filled" : "outlined"}
                  />
                );
              })}
            </Box>
          </Box>

          <ResponsiveContainer width="100%" height={400}>
            <LineChart margin={{ top: 5, right: 30, left: 20, bottom: 5 }}>
              <CartesianGrid strokeDasharray="3 3" />
              <XAxis 
                dataKey="etiqueta" 
                interval={4} 
                angle={-45}
                textAnchor="end"
                height={70}
                type="category"
                allowDuplicatedCategory={false}
                scale="point"
              />
              <YAxis 
                label={{ value: 'Mite population', angle: -90, position: 'insideLeft' }}
                domain={[0, 'auto']}
              />
              <RechartsTooltip 
                formatter={(value, name) => {
                  return [Number(value).toFixed(0), name];
                }}
                labelFormatter={(label) => {
                  return `Date: ${label}`;
                }}
                wrapperStyle={{ zIndex: 1000 }}
              />
              <Legend wrapperStyle={{ paddingTop: 20 }} />
              
              {/* Line without treatment */}
              <Line 
                data={datosGraficaComparativa}
                type="monotone" 
                dataKey="poblacionAcaros" 
                name="Without treatment" 
                stroke="#EB5757" 
                strokeWidth={3}
                dot={false}
                activeDot={{ r: 6 }}
                isAnimationActive={false}
                connectNulls={true}
              />
              
              {/* Lines for each treatment */}
              {datosPorTratamiento.map((item) => {
                const nombreTratamiento = item.tratamiento.nombre || `Treatment`;
                const color = coloresTratamientos[nombreTratamiento];
                const isSelected = tratamientosSeleccionados[item.key] || false;
                
                // Only show selected treatments
                if (!isSelected) return null;
                
                return (
                  <Line 
                    key={item.key}
                    data={item.datos}
                    type="monotone" 
                    dataKey="poblacionAcaros" 
                    name={`${nombreTratamiento} (${item.tratamiento.eficiencia}%)`} 
                    stroke={color} 
                    strokeWidth={2}
                    dot={{ r: 0 }}
                    activeDot={{ r: 6 }}
                    isAnimationActive={false}
                    connectNulls={true}
                  />
                );
              })}
              
              {/* Critical threshold line */}
              <ReferenceLine 
                y={CONSTANTES_VARROA.UMBRAL_INFESTACION_CRITICO * 100} // Convert percentage to number of mites
                stroke={CONSTANTES_VARROA.COLORES.UMBRAL_CRITICO} 
                strokeDasharray="3 3"
                strokeWidth={2}
              >
                <Label 
                  value="Critical level" 
                  position="insideBottomRight"
                  fill={CONSTANTES_VARROA.COLORES.UMBRAL_CRITICO}
                />
              </ReferenceLine>
            </LineChart>
          </ResponsiveContainer>
          
          <Alert severity="info" sx={{ mt: 2 }}>
            <AlertTitle>Graph Interpretation</AlertTitle>
            <Typography variant="body2">
              This graph allows you to compare the effectiveness of the different selected treatments. The lower the line, the more effective the treatment is in controlling the Varroa population. Differences between treatments are more evident in the long term.
            </Typography>
            <Typography variant="body2" sx={{ mt: 1 }}>
              <strong>Note:</strong> Each colored line represents a different treatment, with a population reduction proportional to its efficiency. The red line shows the evolution without any treatment.
            </Typography>
            {Object.values(tratamientosSeleccionados).every(v => !v) && (
              <Typography variant="body2" sx={{ mt: 1, fontStyle: 'italic', color: 'warning.main' }}>
                <strong>Warning:</strong> No treatments are selected. Click on the chips above to show the treatments.
              </Typography>
            )}
          </Alert>
        </Box>

        <Box sx={{ mt: 4 }}>
          <Typography variant="h6" color="primary" gutterBottom sx={{ mt: 2, display: 'flex', alignItems: 'center', gap: 1 }}>
            <InfoIcon /> Recommendations
          </Typography>
          <Typography variant="body1" paragraph>
            {recomendacion}
          </Typography>
        </Box>

        <Box sx={{ mt: 4, p: 2, bgcolor: alpha(theme.palette.info.main, 0.1), borderRadius: 1 }}>
          <Typography variant="h6" color="primary" gutterBottom sx={{ mt: 2, display: 'flex', alignItems: 'center', gap: 1 }}>
            <InfoIcon /> Additional Information
          </Typography>
          <Typography variant="body1" paragraph>
            This predictive model is based on scientific research and provides an estimate of Varroa population growth. Results may vary depending on local conditions, colony management, and environmental factors.
          </Typography>
          <Typography variant="caption" paragraph sx={{ fontStyle: 'italic' }}>
            * This predictive model is based on the work of Dr. Michael Rubinigg. The results are estimates and may vary according to environmental and management factors.
          </Typography>
        </Box>

        <Box sx={{ mt: 4 }}>
          <Typography variant="h6" gutterBottom sx={{ color: theme.palette.success.main }}>
            About Post-Treatment Infestation Peaks
          </Typography>
          <Typography variant="body1" paragraph>
            After applying a treatment, it's normal to observe a temporary peak in the infestation percentage (gray line) and in the natural fall of mites (blue line). This happens because:
          </Typography>
          <List dense>
            <ListItem>
              <ListItemIcon>
                <CheckCircleIcon color="info" fontSize="small" />
              </ListItemIcon>
              <ListItemText primary="The mites that survive the treatment are mainly concentrated on adult bees (phoretic phase)." />
            </ListItem>
            <ListItem>
              <ListItemIcon>
                <CheckCircleIcon color="info" fontSize="small" />
              </ListItemIcon>
              <ListItemText primary="The proportion of mites in the phoretic phase temporarily increases, which raises the visible infestation percentage." />
            </ListItem>
            <ListItem>
              <ListItemIcon>
                <CheckCircleIcon color="info" fontSize="small" />
              </ListItemIcon>
              <ListItemText primary="This effect is transitory and does not necessarily indicate a treatment failure or reinfestation." />
            </ListItem>
          </List>
          <Typography variant="body1" paragraph>
            The points marked with "!" on the graph indicate these post-treatment peaks.
          </Typography>
        </Box>

        <Box sx={{ mt: 4 }}>
          <Typography variant="h6" gutterBottom sx={{ color: theme.palette.success.main }}>
            Additional Information
          </Typography>
          <Typography variant="body1" paragraph>
            This predictive model is based on scientific research and provides an estimate of Varroa population growth. Results may vary depending on local conditions, colony management, and environmental factors.
          </Typography>
          <Typography variant="caption" paragraph sx={{ fontStyle: 'italic' }}>
            * This predictive model is based on the work of Dr. Michael Rubinigg. The results are estimates and may vary according to environmental and management factors.
          </Typography>
        </Box>

        <Typography variant="body2" color="textSecondary" sx={{ mt: 2, fontStyle: 'italic' }}>
          * This predictive model is based on the work of Dr. Michael Rubinigg. The results are estimates and may vary according to environmental and management factors.
        </Typography>

        <Box sx={{ mt: 3, display: 'flex', justifyContent: 'center' }}>
          <Button 
            variant="outlined" 
            color="primary" 
            onClick={handleOpenInfoDialog} 
            startIcon={<InfoIcon />}
            size="large"
          >
            Read more about the predictive model
          </Button>
        </Box>

        <Dialog
          open={openInfoDialog}
          onClose={handleCloseInfoDialog}
          aria-labelledby="alert-dialog-title"
          aria-describedby="alert-dialog-description"
          maxWidth="md"
          fullWidth
        >
          <DialogTitle id="alert-dialog-title" sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
            <ScienceIcon color="primary" />
            Varroa Predictive Model
          </DialogTitle>
          <DialogContent>
            <DialogContentText id="alert-dialog-description" paragraph>
              This advanced predictive model is based on scientific research and allows you to estimate the evolution of the Varroa destructor mite population in a bee colony over time.
            </DialogContentText>
            
            <Typography variant="h6" color="primary" gutterBottom sx={{ mt: 2, display: 'flex', alignItems: 'center', gap: 1 }}>
              <CalculateIcon /> Mathematical Foundations
            </Typography>
            <DialogContentText paragraph>
              The model is based on the standard equation for population growth of organisms with continuous reproduction:
            </DialogContentText>
            <DialogContentText paragraph sx={{ fontWeight: 'bold', fontFamily: 'monospace', pl: 2 }}>
              Nₜ = N₀ × e^(t×Rg)
            </DialogContentText>
            <DialogContentText paragraph>
              Where <strong>Nₜ</strong> is the final number of mites, <strong>N₀</strong> is the initial number, <strong>t</strong> is the time in days, <strong>Rg</strong> is the relative growth rate, and <strong>e</strong> is the mathematical constant (≈2.71828).
            </DialogContentText>
            <DialogContentText paragraph>
              For Varroa, the model is adapted considering specific factors:
            </DialogContentText>
            <DialogContentText paragraph sx={{ fontWeight: 'bold', fontFamily: 'monospace', pl: 2 }}>
              Nₜ = N₀ × e^(t×Rg×Xₜ) × e^(t×Rm×(1+Yₜ))
            </DialogContentText>
            <DialogContentText paragraph>
              Where <strong>Xₜ</strong> is a factor that slows down growth when the competition for brood cells increases, <strong>Rm</strong> is the relative mortality rate, and <strong>Yₜ</strong> is a factor that increases mortality when there is little or no brood available.
            </DialogContentText>
            
            <Typography variant="h6" color="primary" gutterBottom sx={{ mt: 2, display: 'flex', alignItems: 'center', gap: 1 }}>
              <FunctionsIcon /> Model Factors
            </Typography>
            <DialogContentText paragraph>
              <strong>1. Growth rate (Rg):</strong> Varies depending on the season. In spring-summer (March-July) a standard value of 0.03391 new mites per existing mite per day is used, while in summer-autumn (August-October) it may be higher due to mite immigration.
            </DialogContentText>
            <DialogContentText paragraph>
              <strong>2. Slowing factor (Xₜ):</strong> Reduces the growth rate when the probability of more than one mite infesting a brood cell increases. It is calculated as:
            </DialogContentText>
            <DialogContentText paragraph sx={{ fontFamily: 'monospace', pl: 2 }}>
              Xₜ = 100/(100 + e^(Nₜ/Bₜ₋₇))
            </DialogContentText>
            <DialogContentText paragraph>
              Where Bₜ₋₇ is the number of eggs produced by the queen 7 days before.
            </DialogContentText>
            <DialogContentText paragraph>
              <strong>3. Mortality rate (Rm):</strong> Is set to -0.007 mites killed per existing mite per day during the presence of brood.
            </DialogContentText>
            <DialogContentText paragraph>
              <strong>4. Exposure factor (Yₜ):</strong> Estimates the probability of mites being outside brood cells, increasing their mortality. It is calculated as:
            </DialogContentText>
            <DialogContentText paragraph sx={{ fontFamily: 'monospace', pl: 2 }}>
              Yₜ = 2/(1 + e^(Bₜ₋₇/Nₜ))
            </DialogContentText>
            <DialogContentText paragraph>
              <strong>5. Treatment efficiency:</strong> Reduces the mite population according to the percentage of treatment effectiveness.
            </DialogContentText>
            
            <Typography variant="h6" color="primary" gutterBottom sx={{ mt: 2, display: 'flex', alignItems: 'center', gap: 1 }}>
              <FunctionsIcon /> Calculation Methodology
            </Typography>
            <List dense>
              <ListItem>
                <ListItemIcon>
                  <TrendingUpIcon color="primary" />
                </ListItemIcon>
                <ListItemText 
                  primary="Exponential Growth Base" 
                  secondary="The mite population grows exponentially with a reproductive rate (r) that varies depending on the season."
                />
              </ListItem>
              <ListItem>
                <ListItemIcon>
                  <BugReportIcon color="primary" />
                </ListItemIcon>
                <ListItemText 
                  primary="Brood Production Model" 
                  secondary="The availability of brood cells is calculated based on the day of the year, which directly affects mite reproduction."
                />
              </ListItem>
              <ListItem>
                <ListItemIcon>
                  <ThermostatIcon color="primary" />
                </ListItemIcon>
                <ListItemText 
                  primary="Environmental Factors" 
                  secondary="Temperature and other environmental factors modulate the mite reproductive rate."
                />
              </ListItem>
              <ListItem>
                <ListItemIcon>
                  <WarningIcon color="primary" />
                </ListItemIcon>
                <ListItemText 
                  primary="Slowing Factors" 
                  secondary="As infestation increases, slowing factors are applied that reflect competition for resources and potential colony collapse."
                />
              </ListItem>
            </List>

            <Typography variant="h6" color="primary" gutterBottom sx={{ mt: 2, display: 'flex', alignItems: 'center', gap: 1 }}>
              <ScienceIcon /> Scientific References
            </Typography>
            <List dense>
              <ListItem>
                <ListItemIcon>
                  <ScienceIcon fontSize="small" />
                </ListItemIcon>
                <ListItemText 
                  primary="Rubinigg, M. et al. (2020)" 
                  secondary="Development of a population model for the Varroa mite based on its natural mortality."
                />
              </ListItem>
            </List>
            <List dense>
            <ListItem>
              <ListItemIcon>
                <ScienceIcon fontSize="small" />
              </ListItemIcon>
              <ListItemText 
                primary="Beetsma, J., Boot, W. J., & Calis, J. (1999)" 
                secondary="Invasion behaviour of Varroa jacobsoni Oud.: from bees into brood cells."
              />
            </ListItem>
            <ListItem>
              <ListItemIcon>
                <ScienceIcon fontSize="small" />
              </ListItemIcon>
              <ListItemText 
                primary="Boot, W. J., et al. (1995)" 
                secondary="Invasion of Varroa jacobsoni into drone brood cells of the honey bee, Apis mellifera."
              />
            </ListItem>
            <ListItem>
              <ListItemIcon>
                <ScienceIcon fontSize="small" />
              </ListItemIcon>
              <ListItemText 
                primary="Moritz, R. F. A. (1985)" 
                secondary="Heritability of the postcapping stage in Apis mellifera and its relation to varroatosis resistance."
              />
            </ListItem>
            <ListItem>
              <ListItemIcon>
                <ScienceIcon fontSize="small" />
              </ListItemIcon>
              <ListItemText 
                primary="Rosenkranz, P., Aumeier, P., & Ziegelmann, B. (2010)" 
                secondary="Biology and control of Varroa destructor."
              />
            </ListItem>
            <ListItem>
              <ListItemIcon>
                <ScienceIcon fontSize="small" />
              </ListItemIcon>
              <ListItemText 
                primary="Harbo, J. R., & Harris, J. W. (1999)" 
                secondary="Selecting honey bees for resistance to Varroa jacobsoni."
              />
            </ListItem>
            <ListItem>
              <ListItemIcon>
                <ScienceIcon fontSize="small" />
              </ListItemIcon>
              <ListItemText 
                primary="Li, Z., et al. (2016)" 
                secondary="Drone and worker brood microclimates are regulated differentially in honey bees, Apis mellifera."
              />
            </ListItem>
            <ListItem>
              <ListItemIcon>
                <ScienceIcon fontSize="small" />
              </ListItemIcon>
              <ListItemText 
                primary="Starks, P. T., Blackie, C. A., & Seeley, T. D. (2000)" 
                secondary="Fever in honeybee colonies."
              />
            </ListItem>
            <ListItem>
              <ListItemIcon>
                <ScienceIcon fontSize="small" />
              </ListItemIcon>
              <ListItemText 
                primary="Büchler, R., Berg, S., & Le Conte, Y. (2010)" 
                secondary="Breeding for resistance to Varroa destructor in Europe."
              />
            </ListItem>
            <ListItem>
              <ListItemIcon>
                <ScienceIcon fontSize="small" />
              </ListItemIcon>
              <ListItemText 
                primary="Branco, M. R., Kidd, N. A. C., & Pickard, R. S. (2006)" 
                secondary="A comparative evaluation of sampling methods for Varroa destructor population estimation."
              />
            </ListItem>
            <ListItem>
              <ListItemIcon>
                <ScienceIcon fontSize="small" />
              </ListItemIcon>
              <ListItemText 
                primary="Dietemann, V., et al. (2016)" 
                secondary="Standard methods for varroa research."
              />
            </ListItem>
            <ListItem>
              <ListItemIcon>
                <ScienceIcon fontSize="small" />
              </ListItemIcon>
              <ListItemText 
                primary="Martin, S. (1998)" 
                secondary="A population model for the ectoparasitic mite Varroa jacobsoni in honey bee (Apis mellifera) colonies."
              />
            </ListItem>
            <ListItem>
              <ListItemIcon>
                <ScienceIcon fontSize="small" />
              </ListItemIcon>
              <ListItemText 
                primary="Calis, J. N. M., Fries, I., & Ryrie, S. C. (1999)" 
                secondary="Population modelling of Varroa jacobsoni Oud."
              />
            </ListItem>
          </List>
            
          </DialogContent>
          <DialogActions>
            <Button onClick={handleCloseInfoDialog} color="primary" variant="contained">
              Close
            </Button>
          </DialogActions>
        </Dialog>
      </Paper>
    </Box>
  );
};

export default VarroaPredictiveChart;
