import React, { useState, useEffect } from 'react';
import {
  Box,
  Paper,
  Typography,
  useTheme,
  Button,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  List,
  ListItem,
  ListItemText,
  Divider,
  Stack,
  Chip
} from '@mui/material';
import InfoOutlinedIcon from '@mui/icons-material/InfoOutlined';
import {
  LineChart,
  Line,
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  ResponsiveContainer,
  ReferenceLine,
  Area,
  AreaChart,
  RadarChart,
  PolarGrid,
  PolarAngleAxis,
  PolarRadiusAxis,
  Radar
} from 'recharts';

interface Props {
  type?: 'temperature' | 'comparison' | 'risk' | 'lifecycle';
  selectedTreatment?: {
    name: string;
    effectiveness: number;
  };
  temperature?: number;
  infestationRate: number;
  availableTreatments: Array<{
    name: string;
    effectiveness: number;
    duration: number;
    cost: number;
    naturalness: number;
    isRecommended: boolean;
    temperature: {
      min: number;
      max: number;
    };
  }>;
}

interface DialogSection {
  title: string;
  description: string;
}

interface DialogContentType {
  title: string;
  description: string;
  metrics: DialogSection[];
  characteristics?: DialogSection[];
  selectionCriteria?: DialogSection[];
  guidelines?: DialogSection[];
  applications?: DialogSection[];
}

interface DialogContentMap {
  [key: string]: DialogContentType;
}

type DialogType = 'temperature' | 'comparison' | 'risk' | 'lifecycle';

// Datos de efectividad según temperatura
const temperatureData = [
  { temp: 5, effectiveness: 45 },
  { temp: 10, effectiveness: 65 },
  { temp: 15, effectiveness: 85 },
  { temp: 20, effectiveness: 95 },
  { temp: 25, effectiveness: 90 },
  { temp: 30, effectiveness: 75 },
  { temp: 35, effectiveness: 60 }
];

// Datos de niveles de riesgo por mes
const riskLevelData = [
  { month: 'Jan', threshold: 2, critical: 5, actual: 1 },
  { month: 'Feb', threshold: 2, critical: 5, actual: 1.25 },
  { month: 'Mar', threshold: 3, critical: 6, actual: 2 },
  { month: 'Apr', threshold: 3, critical: 6, actual: 4 },
  { month: 'May', threshold: 4, critical: 7, actual: 6 },
  { month: 'Jun', threshold: 4, critical: 7, actual: 7.5 },
  { month: 'Jul', threshold: 5, critical: 8, actual: 12.9 },
  { month: 'Aug', threshold: 5, critical: 8, actual: 20 },
  { month: 'Sep', threshold: 4, critical: 7, actual: 32 },
  { month: 'Oct', threshold: 3, critical: 6, actual: 35 },
  { month: 'Nov', threshold: 2, critical: 5, actual: 33.3 },
  { month: 'Dec', threshold: 2, critical: 5, actual: 33.3 }
];

// Datos del ciclo de vida
const lifecycleData = [
  { stage: 'Egg', duration: 3, vulnerability: 28 },
  { stage: 'Protonymph', duration: 3, vulnerability: 27 },
  { stage: 'Deutonymph', duration: 3, vulnerability: 25 },
  { stage: 'Adult', duration: 27, vulnerability: 18 },
  { stage: 'Reproduction', duration: 30, vulnerability: 22 }
];

const AdditionalCharts: React.FC<Props> = ({
  type = 'temperature',
  selectedTreatment,
  temperature = 20,
  infestationRate,
  availableTreatments
}) => {
  const theme = useTheme();
  const [openDialog, setOpenDialog] = useState<DialogType | null>(null);

  // Inicializar solo con los tratamientos recomendados
  const initialTreatments = availableTreatments
    .filter(t => t.isRecommended)
    .map(t => t.name);

  const [selectedTreatments, setSelectedTreatments] = useState<string[]>(initialTreatments);

  useEffect(() => {
    // Actualizar los tratamientos seleccionados cuando cambien los disponibles
    const recommendedTreatments = availableTreatments
      .filter(t => t.isRecommended)
      .map(t => t.name);
    setSelectedTreatments(recommendedTreatments);
  }, [availableTreatments]);

  const handleOpenDialog = (dialogId: DialogType) => {
    setOpenDialog(dialogId);
  };
  const handleCloseDialog = () => {
    setOpenDialog(null);
  };

  const handleTreatmentToggle = (treatmentName: string) => {
    setSelectedTreatments(prev => 
      prev.includes(treatmentName)
        ? prev.filter(name => name !== treatmentName)
        : [...prev, treatmentName]
    );
  };

  // Función para generar los datos de temperatura para un tratamiento
  const generateTemperatureData = (treatment: any) => {
    const minTemp = treatment.temperature?.min || 0;
    const maxTemp = treatment.temperature?.max || 0;
    const points = [];

    // Generar puntos cada 5 grados
    for (let temp = Math.max(5, minTemp - 5); temp <= Math.min(35, maxTemp + 5); temp += 5) {
      let effectiveness = 0;
      
      // Calcular efectividad basada en la temperatura
      if (temp >= minTemp && temp <= maxTemp) {
        // Máxima efectividad dentro del rango óptimo
        effectiveness = treatment.effectiveness || 0;
      } else if (temp < minTemp) {
        // Disminución gradual por debajo del rango
        effectiveness = Math.max(0, treatment.effectiveness * (1 - (minTemp - temp) / 10));
      } else {
        // Disminución gradual por encima del rango
        effectiveness = Math.max(0, treatment.effectiveness * (1 - (temp - maxTemp) / 10));
      }

      points.push({
        temp,
        effectiveness: Math.round(effectiveness)
      });
    }

    console.log('Generated points for', treatment.name, ':', points);
    return points;
  };

  // Filtrar los datos de comparación según los tratamientos seleccionados
  const filteredTreatmentData = availableTreatments
    .filter(treatment => selectedTreatments.includes(treatment.name));

  const renderChart = () => {
    switch (type) {
      case 'temperature':
        // Filtrar solo los tratamientos seleccionados
        const selectedTreatmentsData = availableTreatments
          .filter(t => selectedTreatments.includes(t.name));

        console.log('Selected Treatments:', selectedTreatments);
        console.log('Available Treatments:', availableTreatments);
        console.log('Filtered Treatments:', selectedTreatmentsData);

        return (
          <Paper elevation={3} sx={{ p: 3, mb: 3 }}>
            <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
              <Typography variant="h6">
                Temperature Impact on Treatment Effectiveness
              </Typography>
              <Button
                startIcon={<InfoOutlinedIcon />}
                onClick={() => handleOpenDialog('temperature')}
                size="small"
                sx={{ color: 'warning.main' }}
              >
                Read More
              </Button>
            </Box>
            
            <Box sx={{ mb: 2 }}>
              <Typography variant="subtitle2" gutterBottom>
                Select treatments to compare:
              </Typography>
              <Stack direction="row" spacing={1} flexWrap="wrap" useFlexGap sx={{ mb: 2 }}>
                {availableTreatments.map(treatment => (
                  <Chip
                    key={treatment.name}
                    label={treatment.name}
                    onClick={() => handleTreatmentToggle(treatment.name)}
                    color={selectedTreatments.includes(treatment.name) ? "primary" : "default"}
                    sx={{
                      bgcolor: selectedTreatments.includes(treatment.name) ? 'primary.light' : 'grey.100',
                      color: selectedTreatments.includes(treatment.name) ? 'white' : 'text.primary',
                      '&:hover': {
                        bgcolor: selectedTreatments.includes(treatment.name) ? 'primary.main' : 'grey.200',
                      }
                    }}
                  />
                ))}
              </Stack>
            </Box>

            <ResponsiveContainer width="100%" height={450}>
              <LineChart margin={{ top: 20, right: 30, left: 20, bottom: 80 }}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis 
                  dataKey="temp" 
                  type="number"
                  domain={['dataMin', 'dataMax']}
                  label={{ 
                    value: 'Temperature (°C)', 
                    position: 'bottom',
                    offset: 50
                  }}
                  tick={{ dy: 10 }}
                />
                <YAxis 
                  label={{ 
                    value: 'Effectiveness (%)', 
                    angle: -90, 
                    position: 'insideLeft',
                    offset: -10
                  }}
                  domain={[0, 100]}
                />
                <Tooltip 
                  formatter={(value: any) => [`${value}%`, 'Effectiveness']}
                  labelFormatter={(label: any) => `Temperature: ${label}°C`}
                />
                <Legend 
                  verticalAlign="bottom"
                  height={36}
                  wrapperStyle={{
                    paddingTop: '30px',
                    bottom: '-10px',
                    fontSize: '12px'
                  }}
                />
                {selectedTreatmentsData.map((treatment, index) => {
                  try {
                    const data = generateTemperatureData(treatment);
                    if (data.length === 0) return null;
                    return (
                      <Line
                        key={treatment.name}
                        name={treatment.name}
                        data={data}
                        type="monotone"
                        dataKey="effectiveness"
                        stroke={theme.palette.warning[index % 2 ? 'light' : 'main']}
                        strokeWidth={2}
                        dot={{ 
                          fill: theme.palette.warning[index % 2 ? 'light' : 'main'],
                          r: 4
                        }}
                        activeDot={{
                          r: 8,
                          fill: theme.palette.warning[index % 2 ? 'light' : 'main'],
                          stroke: '#fff'
                        }}
                      />
                    );
                  } catch (error) {
                    console.error('Error generating data for treatment:', treatment, error);
                    return null;
                  }
                })}
                <ReferenceLine
                  x={temperature}
                  stroke={theme.palette.warning.dark}
                  strokeDasharray="3 3"
                  label={{
                    value: 'Current',
                    position: 'top',
                    fill: theme.palette.warning.dark
                  }}
                />
              </LineChart>
            </ResponsiveContainer>
          </Paper>
        );
      case 'comparison':
        return (
          <Paper elevation={3} sx={{ p: 3, mb: 3 }}>
            <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
              <Typography variant="h6">
                Treatment Comparison
              </Typography>
              <Button
                startIcon={<InfoOutlinedIcon />}
                onClick={() => handleOpenDialog('comparison')}
                size="small"
                sx={{ color: 'warning.main' }}
              >
                Read More
              </Button>
            </Box>
            <Box sx={{ mb: 2 }}>
              <Typography variant="subtitle2" gutterBottom>
                Select treatments to compare:
              </Typography>
              <Stack direction="row" spacing={1} flexWrap="wrap" useFlexGap>
                {availableTreatments.map(treatment => (
                  <Chip
                    key={treatment.name}
                    label={treatment.name}
                    onClick={() => handleTreatmentToggle(treatment.name)}
                    color={selectedTreatments.includes(treatment.name) ? "primary" : "default"}
                    sx={{
                      bgcolor: selectedTreatments.includes(treatment.name) ? 'primary.light' : 'grey.100',
                      color: selectedTreatments.includes(treatment.name) ? 'white' : 'text.primary',
                      '&:hover': {
                        bgcolor: selectedTreatments.includes(treatment.name) ? 'primary.main' : 'grey.200',
                      }
                    }}
                  />
                ))}
              </Stack>
              <ResponsiveContainer width="100%" height={400}>
                <RadarChart cx="50%" cy="50%" outerRadius="80%" data={filteredTreatmentData}>
                  <PolarGrid />
                  <PolarAngleAxis dataKey="name" />
                  <PolarRadiusAxis angle={30} domain={[0, 100]} />
                  <Radar
                    name="Effectiveness"
                    dataKey="effectiveness"
                    stroke={theme.palette.primary.main}
                    fill={theme.palette.primary.main}
                    fillOpacity={0.3}
                  />
                  <Radar
                    name="Duration"
                    dataKey="duration"
                    stroke={theme.palette.warning.main}
                    fill={theme.palette.warning.main}
                    fillOpacity={0.3}
                  />
                  <Radar
                    name="Naturalness"
                    dataKey="naturalness"
                    stroke={theme.palette.success.main}
                    fill={theme.palette.success.main}
                    fillOpacity={0.3}
                  />
                  <Legend />
                  <Tooltip />
                </RadarChart>
              </ResponsiveContainer>
            </Box>
          </Paper>
        );
      case 'risk':
        return (
          <Paper elevation={3} sx={{ p: 3, mb: 3 }}>
            <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
              <Typography variant="h6">
                Risk Levels Throughout the Year
              </Typography>
              <Button
                startIcon={<InfoOutlinedIcon />}
                onClick={() => handleOpenDialog('risk')}
                size="small"
                sx={{
                  color: 'warning.main',
                  '&:hover': {
                    backgroundColor: 'transparent',
                    color: 'warning.dark',
                  }
                }}
              >
                Read More
              </Button>
            </Box>
            <ResponsiveContainer width="100%" height={300}>
              <AreaChart data={riskLevelData}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="month" />
                <YAxis label={{ value: 'Mites per 100 Bees', angle: -90, position: 'insideLeft' }} />
                <Tooltip />
                <Legend />
                <Area
                  type="monotone"
                  dataKey="threshold"
                  stackId="1"
                  stroke="#FFB74D"
                  fill="#FFE0B2"
                  name="Warning Threshold"
                />
                <Area
                  type="monotone"
                  dataKey="critical"
                  stackId="1"
                  stroke="#EF5350"
                  fill="#FFCDD2"
                  name="Critical Threshold"
                />
                <Line
                  type="monotone"
                  dataKey="actual"
                  stroke="#2196F3"
                  strokeWidth={2}
                  name="Actual Level"
                />
              </AreaChart>
            </ResponsiveContainer>
          </Paper>
        );
      case 'lifecycle':
        return (
          <Paper elevation={3} sx={{ p: 3, mb: 3 }}>
            <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
              <Typography variant="h6">
                Varroa Life Cycle and Treatment Vulnerability
              </Typography>
              <Button
                startIcon={<InfoOutlinedIcon />}
                onClick={() => handleOpenDialog('lifecycle')}
                size="small"
                sx={{ color: 'warning.main' }}
              >
                Read More
              </Button>
            </Box>
            <ResponsiveContainer width="100%" height={300}>
              <BarChart data={lifecycleData}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="stage" />
                <YAxis yAxisId="left" orientation="left" stroke={theme.palette.warning.light} />
                <YAxis yAxisId="right" orientation="right" stroke={theme.palette.warning.main} />
                <Tooltip />
                <Legend />
                <Bar yAxisId="left" dataKey="duration" name="Duration (days)" fill={theme.palette.warning.light} />
                <Bar yAxisId="right" dataKey="vulnerability" name="Treatment Vulnerability (%)" fill={theme.palette.warning.main} />
              </BarChart>
            </ResponsiveContainer>
          </Paper>
        );
      default:
        return null;
    }
  };

  // Contenido detallado para cada diálogo
  const dialogContent: DialogContentMap = {
    temperature: {
      title: 'Temperature Impact on Treatment Effectiveness',
      description: 'This graph illustrates the relationship between ambient temperature and treatment effectiveness. The curve represents the optimal temperature range for varroa treatment application.',
      metrics: [
        {
          title: 'Optimal Temperature Range',
          description: '15-25°C (59-77°F)'
        },
        {
          title: 'Peak Effectiveness',
          description: 'Around 20°C (68°F)'
        },
        {
          title: 'Treatment Efficacy',
          description: 'Decreases significantly below 10°C and above 30°C'
        },
        {
          title: 'Professional Insights',
          description: 'Temperature affects both varroa mite metabolism and the volatilization rate of treatment compounds. In organic acids and essential oils treatments, temperature plays a crucial role in vapor pressure and distribution throughout the hive.'
        }
      ],
      characteristics: [
        {
          title: 'Practical Applications',
          description: 'Plan treatments during periods of optimal temperature'
        },
        {
          title: 'Treatment Duration',
          description: 'Consider extended treatment duration if temperatures are suboptimal'
        },
        {
          title: 'Weather Monitoring',
          description: 'Monitor weather forecasts before treatment application'
        },
        {
          title: 'Application Timing',
          description: 'Early morning or late evening applications may be preferable during hot periods'
        }
      ]
    },
    comparison: {
      title: 'Treatment Comparison Analysis',
      description: 'This radar chart provides a multi-dimensional comparison of different varroa treatments across four key metrics: effectiveness, treatment duration, cost, and naturalness.',
      metrics: [
        {
          title: 'Effectiveness',
          description: 'Percentage of mite population eliminated'
        },
        {
          title: 'Duration',
          description: 'Length of treatment period in days'
        },
        {
          title: 'Cost',
          description: 'Relative economic investment required'
        },
        {
          title: 'Naturalness',
          description: 'Degree of chemical synthesis and environmental impact'
        }
      ],
      characteristics: [
        {
          title: 'Oxuvar®',
          description: 'High effectiveness, short duration, moderate cost, very natural'
        },
        {
          title: 'Apivar®',
          description: 'Highest effectiveness, longest duration, highest cost, less natural'
        },
        {
          title: 'Apiguard®',
          description: 'Good balance of all parameters'
        },
        {
          title: 'Thymovar®',
          description: 'Most natural, moderate effectiveness, medium duration'
        }
      ],
      selectionCriteria: [
        {
          title: 'Selection Criteria',
          description: 'Consider these factors when choosing a treatment:'
        },
        {
          title: 'Temperature',
          description: 'Season and temperature requirements'
        },
        {
          title: 'Honey Production',
          description: 'Presence of honey supers'
        },
        {
          title: 'Resistance',
          description: 'Resistance management'
        },
        {
          title: 'Regulations',
          description: 'Local regulations and organic certification requirements'
        }
      ]
    },
    risk: {
      title: 'Annual Risk Level Assessment',
      description: 'This graph displays three critical zones for varroa infestation levels throughout the year.',
      metrics: [
        {
          title: 'Safe Zone (Below Yellow)',
          description: 'Normal mite levels, monitoring required'
        },
        {
          title: 'Warning Zone (Yellow)',
          description: 'Action threshold reached, treatment planning needed'
        },
        {
          title: 'Critical Zone (Red)',
          description: 'Immediate intervention required to prevent colony loss'
        }
      ],
      characteristics: [
        {
          title: 'Spring',
          description: 'Slow population growth as brood rearing increases'
        },
        {
          title: 'Summer',
          description: 'Exponential growth during peak brood season'
        },
        {
          title: 'Fall',
          description: 'Highest risk period as bee population decreases'
        },
        {
          title: 'Winter',
          description: 'Natural decline but potential for dangerous concentrations'
        }
      ],
      guidelines: [
        {
          title: 'Monitoring Frequency',
          description: 'Monthly mite counts recommended during active season'
        },
        {
          title: 'Warning Zone Protocol',
          description: 'Increase monitoring frequency when approaching warning zone'
        },
        {
          title: 'Treatment Planning',
          description: 'Consider pre-emptive treatments based on historical patterns'
        },
        {
          title: 'Documentation',
          description: 'Document treatment timing and effectiveness for future planning'
        }
      ]
    },
    lifecycle: {
      title: 'Varroa Life Cycle and Treatment Vulnerability',
      description: 'This dual-axis graph shows both the duration of each varroa life phase and its vulnerability to treatments.',
      metrics: [
        {
          title: 'Egg (3 days)',
          description: 'Highly vulnerable but protected in brood cells'
        },
        {
          title: 'Protonymph (2.5 days)',
          description: 'Development stage with high metabolic activity'
        },
        {
          title: 'Deutonymph (2.5 days)',
          description: 'Pre-adult stage with increasing resilience'
        },
        {
          title: 'Adult (27 days)',
          description: 'Reproductive phase with varying vulnerability'
        },
        {
          title: 'Reproduction (30 days)',
          description: 'Critical phase for population growth'
        }
      ],
      characteristics: [
        {
          title: 'Treatment Timing',
          description: 'Target treatments during high-vulnerability phases'
        },
        {
          title: 'Treatment Cycles',
          description: 'Consider multiple treatment cycles to affect all life stages'
        },
        {
          title: 'Brood Coordination',
          description: 'Coordinate with bee brood cycles for maximum effectiveness'
        },
        {
          title: 'Temperature Effects',
          description: 'Account for temperature effects on development speed'
        }
      ],
      applications: [
        {
          title: 'Treatment Selection',
          description: 'Use phase knowledge for treatment selection'
        },
        {
          title: 'Duration Planning',
          description: 'Plan treatment duration based on complete life cycle'
        },
        {
          title: 'Management Strategy',
          description: 'Consider integrated pest management strategies'
        },
        {
          title: 'Monitoring',
          description: 'Monitor post-treatment effectiveness across phases'
        }
      ]
    }
  };

  // Array de colores distintos para las líneas
  const lineColors = [
    '#FF6B6B', // rojo coral
    '#4ECDC4', // turquesa
    '#45B7D1', // azul cielo
    '#96CEB4', // verde menta
    '#FFEEAD', // amarillo pastel
    '#D4A5A5', // rosa pálido
    '#9B59B6', // morado
    '#3498DB', // azul brillante
    '#E67E22', // naranja
    '#2ECC71'  // verde esmeralda
  ];

  return (
    <Box sx={{ mt: 4 }}>
      {renderChart()}
      {/* Information Dialog */}
      <Dialog 
        open={openDialog !== null} 
        onClose={handleCloseDialog} 
        maxWidth="md"
        PaperProps={{
          sx: {
            borderRadius: 2,
            maxWidth: '800px',
            width: '100%'
          }
        }}
      >
        {openDialog && (() => {
          const content = dialogContent[openDialog];
          if (!content) return null;
          
          return (
            <>
              <DialogTitle 
                sx={{ 
                  bgcolor: '#f5a623',
                  color: 'white',
                  fontSize: '1.5rem',
                  fontWeight: 500,
                  p: 2
                }}
              >
                {content.title}
              </DialogTitle>
              <DialogContent sx={{ p: 3 }}>
                <Typography paragraph color="text.secondary" sx={{ mb: 3 }}>
                  {content.description}
                </Typography>

                <Typography variant="h6" sx={{ color: '#f5a623', fontSize: '1.25rem', mb: 2, mt: 4 }}>
                  Metrics Explained
                </Typography>
                <List>
                  {content.metrics.map((metric, index) => (
                    <ListItem key={index}>
                      <ListItemText
                        primary={<Typography variant="subtitle1" sx={{ color: 'text.primary', fontWeight: 500 }}>{metric.title}</Typography>}
                        secondary={<Typography variant="body2" sx={{ color: 'text.secondary' }}>{metric.description}</Typography>}
                      />
                    </ListItem>
                  ))}
                </List>

                {content.characteristics && content.characteristics.length > 0 && (
                  <>
                    <Typography variant="h6" sx={{ color: '#f5a623', fontSize: '1.25rem', mb: 2, mt: 4 }}>
                      Treatment Characteristics
                    </Typography>
                    <Typography paragraph sx={{ color: 'text.secondary', mb: 2 }}>
                      Each treatment has its unique profile based on its active ingredients and application method:
                    </Typography>
                    <List>
                      {content.characteristics.map((char, index) => (
                        <ListItem key={index}>
                          <ListItemText
                            primary={<Typography variant="subtitle1" sx={{ color: 'text.primary', fontWeight: 500 }}>{char.title}</Typography>}
                            secondary={<Typography variant="body2" sx={{ color: 'text.secondary' }}>{char.description}</Typography>}
                          />
                        </ListItem>
                      ))}
                    </List>
                  </>
                )}
                {content.selectionCriteria && content.selectionCriteria.length > 0 && (
                  <>
                    <Typography variant="h6" sx={{ color: '#f5a623', fontSize: '1.25rem', mb: 2, mt: 4 }}>
                      Selection Criteria
                    </Typography>
                    <Typography paragraph sx={{ color: 'text.secondary', mb: 2 }}>
                      Consider these factors when choosing a treatment:
                    </Typography>
                    <List>
                      {content.selectionCriteria.map((char, index) => (
                        <ListItem key={index}>
                          <ListItemText
                            primary={<Typography variant="subtitle1" sx={{ color: 'text.primary', fontWeight: 500 }}>{char.title}</Typography>}
                            secondary={<Typography variant="body2" sx={{ color: 'text.secondary' }}>{char.description}</Typography>}
                          />
                        </ListItem>
                      ))}
                    </List>
                  </>
                )}
                {content.guidelines && content.guidelines.length > 0 && (
                  <>
                    <Typography variant="h6" sx={{ color: '#f5a623', fontSize: '1.25rem', mb: 2, mt: 4 }}>
                      Guidelines
                    </Typography>
                    <Typography paragraph sx={{ color: 'text.secondary', mb: 2 }}>
                      Follow these guidelines for effective risk management:
                    </Typography>
                    <List>
                      {content.guidelines.map((char, index) => (
                        <ListItem key={index}>
                          <ListItemText
                            primary={<Typography variant="subtitle1" sx={{ color: 'text.primary', fontWeight: 500 }}>{char.title}</Typography>}
                            secondary={<Typography variant="body2" sx={{ color: 'text.secondary' }}>{char.description}</Typography>}
                          />
                        </ListItem>
                      ))}
                    </List>
                  </>
                )}
                {content.applications && content.applications.length > 0 && (
                  <>
                    <Typography variant="h6" sx={{ color: '#f5a623', fontSize: '1.25rem', mb: 2, mt: 4 }}>
                      Applications
                    </Typography>
                    <Typography paragraph sx={{ color: 'text.secondary', mb: 2 }}>
                      Consider these applications for effective treatment:
                    </Typography>
                    <List>
                      {content.applications.map((char, index) => (
                        <ListItem key={index}>
                          <ListItemText
                            primary={<Typography variant="subtitle1" sx={{ color: 'text.primary', fontWeight: 500 }}>{char.title}</Typography>}
                            secondary={<Typography variant="body2" sx={{ color: 'text.secondary' }}>{char.description}</Typography>}
                          />
                        </ListItem>
                      ))}
                    </List>
                  </>
                )}
              </DialogContent>
              <DialogActions sx={{ p: 2, borderTop: 1, borderColor: 'divider' }}>
                <Button 
                  onClick={handleCloseDialog}
                  sx={{ 
                    color: '#f5a623',
                    '&:hover': {
                      backgroundColor: 'rgba(245, 166, 35, 0.08)',
                      color: '#d48c1f',
                    }
                  }}
                >
                  Close
                </Button>
              </DialogActions>
            </>
          );
        })()}
      </Dialog>
    </Box>
  );
};

export default AdditionalCharts;
