import React from 'react';
import {
  LineChart,
  Line,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  ResponsiveContainer,
  ReferenceLine,
  Label
} from 'recharts';
import { Box, Paper, Typography, useTheme } from '@mui/material';

interface PopulationData {
  month: string;
  bees: number;
  mites: number;
  mitesPerHundred: number;
  predictedMites?: number;
  predictedMitesPerHundred?: number;
}

// Datos para la gráfica de población normal con resolución quincenal
const normalPopulationData: PopulationData[] = [
  { month: '1 Jan', bees: 10000, mites: 100, mitesPerHundred: 1 },
  { month: '15 Jan', bees: 11000, mites: 120, mitesPerHundred: 1.1 },
  { month: '1 Feb', bees: 12000, mites: 150, mitesPerHundred: 1.25 },
  { month: '15 Feb', bees: 13000, mites: 200, mitesPerHundred: 1.54 },
  { month: '1 Mar', bees: 15000, mites: 300, mitesPerHundred: 2 },
  { month: '15 Mar', bees: 17000, mites: 400, mitesPerHundred: 2.35 },
  { month: '1 Apr', bees: 20000, mites: 600, mitesPerHundred: 3 },
  { month: '15 Apr', bees: 23000, mites: 800, mitesPerHundred: 3.48 },
  { month: '1 May', bees: 30000, mites: 1500, mitesPerHundred: 5 },
  { month: '15 May', bees: 35000, mites: 2000, mitesPerHundred: 5.71 },
  { month: '1 Jun', bees: 40000, mites: 3000, mitesPerHundred: 7.5 },
  { month: '15 Jun', bees: 41000, mites: 3500, mitesPerHundred: 8.54 },
  { month: '1 Jul', bees: 35000, mites: 4000, mitesPerHundred: 11.43 },
  { month: '15 Jul', bees: 32000, mites: 4500, mitesPerHundred: 14.06 },
  { month: '1 Aug', bees: 30000, mites: 5000, mitesPerHundred: 16.67 },
  { month: '15 Aug', bees: 28000, mites: 6000, mitesPerHundred: 21.43 },
  { month: '1 Sep', bees: 25000, mites: 7000, mitesPerHundred: 28 },
  { month: '15 Sep', bees: 23000, mites: 7500, mitesPerHundred: 32.61 },
  { month: '1 Oct', bees: 20000, mites: 7000, mitesPerHundred: 35 },
  { month: '16 Oct', bees: 18000, mites: 6500, mitesPerHundred: 36.11 },
  { month: '1 Nov', bees: 15000, mites: 5000, mitesPerHundred: 33.33 },
  { month: '15 Nov', bees: 13000, mites: 4500, mitesPerHundred: 34.62 },
  { month: '1 Dec', bees: 12000, mites: 4000, mitesPerHundred: 33.33 },
  { month: '15 Dec', bees: 11000, mites: 3500, mitesPerHundred: 31.82 }
];

interface VarroaPopulationChartsProps {
  selectedTreatment?: {
    name: string;
    effectiveness: number;
  };
  assessmentDate: string;
  infestationRate: number;
  showTreatmentPrediction?: boolean;
  historicalData?: Array<{
    fecha: string;
    tasa: number;
    estado: string;
    timestamp: number;
  }>;
}

const VarroaPopulationCharts: React.FC<VarroaPopulationChartsProps> = ({
  selectedTreatment,
  assessmentDate,
  infestationRate,
  showTreatmentPrediction = false,
  historicalData = []
}) => {
  const theme = useTheme();
  
  // Obtener el índice del punto más cercano a la fecha de evaluación
  const assessmentDateObj = new Date(assessmentDate);
  const assessmentDay = assessmentDateObj.getDate();
  const assessmentMonth = assessmentDateObj.getMonth();
  
  const getAssessmentIndex = () => {
    const monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
    const index = normalPopulationData.findIndex(data => {
      const [day, monthStr] = data.month.split(' ');
      const monthIndex = monthNames.indexOf(monthStr);
      return monthIndex === assessmentMonth && parseInt(day) >= assessmentDay;
    });
    
    return index === -1 ? normalPopulationData.length - 1 : index;
  };

  const assessmentIndex = getAssessmentIndex();
  
  // Calcula los datos de predicción basados en el tratamiento seleccionado
  const calculatePredictionData = (): PopulationData[] => {
    if (!selectedTreatment) return normalPopulationData;

    if (assessmentIndex < 0 || assessmentIndex >= normalPopulationData.length) {
      console.error('Invalid assessment index:', assessmentIndex);
      return normalPopulationData;
    }

    let calculatedData: PopulationData[] = [];

    // Ajustar los datos normales según la tasa de infestación real medida
    const adjustmentFactor = infestationRate / normalPopulationData[assessmentIndex].mitesPerHundred;

    return normalPopulationData.map((data, index) => {
      // Ajustar los valores base según la medición real
      const adjustedMites = data.mites * adjustmentFactor;
      const adjustedMitesPerHundred = (adjustedMites / data.bees) * 100;

      if (index === assessmentIndex) {
        // Punto de aplicación del tratamiento: caída brusca
        const reductionFactor = selectedTreatment.effectiveness / 100;
        const reducedMites = adjustedMites * (1 - reductionFactor);
        const reducedMitesPerHundred = (reducedMites / data.bees) * 100;

        const result = {
          ...data,
          mites: adjustedMites,
          mitesPerHundred: adjustedMitesPerHundred,
          predictedMites: reducedMites,
          predictedMitesPerHundred: reducedMitesPerHundred
        };
        calculatedData[index] = result;
        return result;
      } else if (index > assessmentIndex) {
        // Después del tratamiento: crecimiento más lento
        const previousData = calculatedData[index - 1];
        const growthRate = 0.1; // Tasa de crecimiento reducida después del tratamiento
        
        let newMites;
        if (previousData?.predictedMites) {
          newMites = previousData.predictedMites * (1 + growthRate);
        } else {
          newMites = adjustedMites;
        }
        
        const newMitesPerHundred = (newMites / data.bees) * 100;

        const result = {
          ...data,
          mites: adjustedMites,
          mitesPerHundred: adjustedMitesPerHundred,
          predictedMites: newMites,
          predictedMitesPerHundred: newMitesPerHundred
        };
        calculatedData[index] = result;
        return result;
      }

      // Antes del tratamiento: usar valores ajustados
      const result = {
        ...data,
        mites: adjustedMites,
        mitesPerHundred: adjustedMitesPerHundred,
        predictedMites: adjustedMites,
        predictedMitesPerHundred: adjustedMitesPerHundred
      };
      calculatedData[index] = result;
      return result;
    });
  };

  const predictionData = calculatePredictionData();
  const assessmentPoint = normalPopulationData[assessmentIndex];

  return (
    <Box sx={{ mt: 4 }}>
      <Paper elevation={3} sx={{ p: 3 }}>
        <Typography 
          variant="h6" 
          gutterBottom
          sx={{ 
            display: 'flex',
            alignItems: 'center',
            gap: 1,
            color: '#F2994A',
            fontWeight: 600
          }}
        >
          
        </Typography>
        
        {/* Primera gráfica */}
        <Typography variant="subtitle1" gutterBottom>
          Normal Population Growth
        </Typography>
        <ResponsiveContainer width="100%" height={300}>
          <LineChart data={normalPopulationData} margin={{ top: 5, right: 30, left: 20, bottom: 5 }}>
            <CartesianGrid strokeDasharray="3 3" />
            <XAxis 
              dataKey="month" 
              interval={1} 
              angle={-45}
              textAnchor="end"
              height={70}
            />
            <YAxis yAxisId="left" orientation="left" stroke="#FFA726" />
            <YAxis yAxisId="right" orientation="right" stroke="#EF5350" />
            <Tooltip />
            <Legend />
            <Line
              yAxisId="left"
              type="monotone"
              dataKey="bees"
              name="Bees"
              stroke="#FFA726"
              activeDot={{ r: 8 }}
            />
            <Line
              yAxisId="right"
              type="monotone"
              dataKey="mites"
              name="Mites"
              stroke="#EF5350"
              activeDot={{ r: 8 }}
            />
          </LineChart>
        </ResponsiveContainer>

        {/* Segunda gráfica */}
        <Typography variant="subtitle1" gutterBottom sx={{ mt: 4 }}>
          Treatment Prediction
        </Typography>
        <ResponsiveContainer width="100%" height={300}>
          <LineChart data={predictionData} margin={{ top: 5, right: 30, left: 20, bottom: 5 }}>
            <CartesianGrid strokeDasharray="3 3" />
            <XAxis 
              dataKey="month" 
              interval={1} 
              angle={-45}
              textAnchor="end"
              height={70}
            />
            <YAxis />
            <Tooltip />
            <Legend />
            <Line
              type="monotone"
              dataKey="mitesPerHundred"
              name="Current Trend"
              stroke="#EF5350"
              strokeWidth={2}
              dot={false}
            />
            <Line
              type="monotone"
              dataKey="predictedMitesPerHundred"
              name="After Treatment"
              stroke="#4CAF50"
              strokeWidth={2}
              strokeDasharray="5 5"
              dot={false}
            />
            <ReferenceLine
              x={assessmentPoint.month}
              stroke="#2196F3"
              strokeDasharray="3 3"
              label={
                <Label
                  value="Treatment"
                  position="top"
                  fill="#2196F3"
                />
              }
            />
          </LineChart>
        </ResponsiveContainer>
      </Paper>
    </Box>
  );
};

export default VarroaPopulationCharts;
