import React, { useState } 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;
  }>;
}

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 = [
  { phase: 'Huevo', duration: 3, vulnerability: 90 },
  { phase: 'Protoninfa', duration: 2.5, vulnerability: 85 },
  { phase: 'Deutoninfa', duration: 2.5, vulnerability: 80 },
  { phase: 'Adulta', duration: 27, vulnerability: 60 },
  { phase: 'Reproducción', duration: 30, vulnerability: 70 }
];

const AdditionalCharts: React.FC<Props> = ({
  type,
  selectedTreatment,
  temperature = 20,
  infestationRate,
  availableTreatments
}) => {
  const theme = useTheme();
  const [openDialog, setOpenDialog] = useState<DialogType | null>(null);
  const [selectedTreatments, setSelectedTreatments] = useState<string[]>(
    availableTreatments
      .filter(t => t.isRecommended || t.name === selectedTreatment?.name)
      .map(t => t.name)
  );

  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]
    );
  };

  // 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':
        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',
                  '&:hover': {
                    backgroundColor: 'transparent',
                    color: 'warning.dark',
                  }
                }}
              >
                Read More
              </Button>
            </Box>
            <ResponsiveContainer width="100%" height={300}>
              <LineChart data={temperatureData}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis
                  dataKey="temp"
                  label={{ value: 'Temperature (°C)', position: 'bottom', offset: 0 }}
                />
                <YAxis
                  label={{ value: 'Effectiveness (%)', angle: -90, position: 'insideLeft' }}
                />
                <Tooltip />
                <Line
                  type="monotone"
                  dataKey="effectiveness"
                  stroke="#2196F3"
                  strokeWidth={2}
                  dot={{ strokeWidth: 2 }}
                />
                <ReferenceLine
                  x={temperature}
                  stroke="red"
                  strokeDasharray="3 3"
                  label={{ value: 'Current', position: 'top' }}
                />
              </LineChart>
            </ResponsiveContainer>
          </Paper>
        );
      case 'comparison':
        return (
          <Box sx={{ width: '100%', p: 2 }}>
            <Paper 
              elevation={3}
              sx={{ 
                p: 3,
                borderRadius: 2,
                bgcolor: 'background.paper',
                boxShadow: '0px 2px 4px rgba(0, 0, 0, 0.1)'
              }}
            >
              <Box sx={{ 
                display: 'flex', 
                justifyContent: 'space-between', 
                alignItems: 'center',
                mb: 2
              }}>
                <Typography variant="h6" component="h2">
                  Treatment Comparison
                </Typography>
                <Button
                  onClick={() => handleOpenDialog('comparison')}
                  startIcon={<InfoOutlinedIcon />}
                  sx={{ 
                    color: 'warning.main',
                    '&:hover': {
                      backgroundColor: 'warning.light',
                    }
                  }}
                >
                  Read More
                </Button>
              </Box>

              <Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
                Compare available treatments (click to show/hide)
              </Typography>
              <Stack direction="row" spacing={1} sx={{ mb: 3 }}>
                {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>
            </Paper>
          </Box>
        );
      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 }}>
            <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',
                  '&:hover': {
                    backgroundColor: 'transparent',
                    color: 'warning.dark',
                  }
                }}
              >
                Read More
              </Button>
            </Box>
            <ResponsiveContainer width="100%" height={300}>
              <BarChart data={lifeCycleData}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="phase" />
                <YAxis yAxisId="left" orientation="left" label={{ value: 'Duration (days)', angle: -90, position: 'insideLeft' }} />
                <YAxis yAxisId="right" orientation="right" label={{ value: 'Vulnerability (%)', angle: 90, position: 'insideRight' }} />
                <Tooltip />
                <Legend />
                <Bar yAxisId="left" dataKey="duration" fill="#4CAF50" name="Duration" />
                <Bar yAxisId="right" dataKey="vulnerability" fill="#2196F3" name="Treatment Vulnerability" />
              </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'
        }
      ]
    }
  };

  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;
