import React, { useState, useEffect, useCallback } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { useNavigate } from 'react-router-dom';
import { RootState } from '../../../store/store';
import { Box, Card, CardContent, Typography, Grid, Divider, Chip, Stack, List, ListItem, ListItemIcon, ListItemText, Paper, Table, TableBody, TableCell, TableContainer, TableHead, TableRow, Button, Dialog, DialogTitle, DialogContent, DialogContentText, DialogActions, Snackbar, Alert, alpha, TextField, IconButton } from '@mui/material';
import EditIcon from '@mui/icons-material/Edit';
import { auth } from '../../../config/firebase';
import { Timestamp } from 'firebase/firestore';
import { saveVarroaTest, VarroaTest } from '../../../services/reportService';
import { resetVarrometerState } from '../../../store/varrometerSlice';
import AssignmentIcon from '@mui/icons-material/Assignment';
import AgricultureIcon from '@mui/icons-material/Agriculture';
import AccessTimeIcon from '@mui/icons-material/AccessTime';
import HomeIcon from '@mui/icons-material/Home';
import BugReportIcon from '@mui/icons-material/BugReport';
import ScienceIcon from '@mui/icons-material/Science';
import LocalPharmacyIcon from '@mui/icons-material/LocalPharmacy';
import CalendarTodayIcon from '@mui/icons-material/CalendarToday';
import GridOnIcon from '@mui/icons-material/GridOn';
import FilterListIcon from '@mui/icons-material/FilterList';
import WarningIcon from '@mui/icons-material/Warning';
import TimerIcon from '@mui/icons-material/Timer';
import LocalHospitalIcon from '@mui/icons-material/LocalHospital';
import ThermostatIcon from '@mui/icons-material/Thermostat';
import ScheduleIcon from '@mui/icons-material/Schedule';
import BeehiveIcon from '@mui/icons-material/Yard';
import ErrorOutlineIcon from '@mui/icons-material/ErrorOutline';
import ReportProblemIcon from '@mui/icons-material/ReportProblem';
import CheckCircleIcon from '@mui/icons-material/CheckCircle';
import VarroaMeter from '../../varrometer/VarroaMeter';
import VarroaPopulationCharts from '../VarroaPopulationCharts';
import AdditionalCharts from '../AdditionalCharts';
import { HiveType, TimePerHive, GeneticResistance } from '../../../types/varrometer';
import { loadTreatmentsFromCSV } from '../../../data/treatmentsData';
import SettingsIcon from '@mui/icons-material/Settings';
import TreatmentReportPDF from '../TreatmentReportPDF';
import { MonitoringRecord, VarrometerTreatment as ImportedVarrometerTreatment } from '../../../types/varrometer';
import InfoIcon from '@mui/icons-material/Info';
import ArrowRightIcon from '@mui/icons-material/ArrowRight';
import CheckCircleOutlineIcon from '@mui/icons-material/CheckCircleOutline';
import { MONITORING_METHODS } from '../../../constants/monitoringMethods';
import VarroaPredictiveChart from '../VarroaPredictiveChart';
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';
import ExpandLessIcon from '@mui/icons-material/ExpandLess';
import VisibilityIcon from '@mui/icons-material/Visibility';
import VisibilityOffIcon from '@mui/icons-material/VisibilityOff';

interface TreatmentCardProps {
  treatment: ImportedVarrometerTreatment;
}

interface Treatment {
  name: string;
  effectiveness: number;
  duration: number;
  relativeCost: number;
  naturalness: number;
  isAvailable: boolean;
  temperature: {
    min: number;
    max: number;
  };
}

interface VarrometerTreatment extends ImportedVarrometerTreatment {}

const TreatmentCard: React.FC<TreatmentCardProps> = ({ treatment }) => {
  // Determine card color based on treatment type
  const getCardColor = () => {
    if (!treatment.type) return '#9e9e9e';
    
    switch (treatment.type) {
      case 'Mechanical methods':
        return '#4caf50'; // green
      case 'Bio-technical methods':
        return '#2196f3'; // blue
      case 'Organic Chemical':
        return '#8bc34a'; // light green
      case 'Synthetic Chemical':
        return '#f44336'; // red
      default:
        return '#9e9e9e'; // grey
    }
  };

  // Get chip color based on treatment type
  const getChipColor = () => {
    if (!treatment.type) return 'default';
    
    switch (treatment.type) {
      case 'Mechanical methods':
        return 'success';
      case 'Bio-technical methods':
        return 'info';
      case 'Organic Chemical':
        return 'success';
      case 'Synthetic Chemical':
        return 'error';
      default:
        return 'default';
    }
  };

  // Get icon based on treatment type
  const getTypeIcon = () => {
    if (!treatment.type) return <InfoIcon />;
    
    switch (treatment.type) {
      case 'Mechanical methods':
        return <SettingsIcon />;
      case 'Bio-technical methods':
        return <BeehiveIcon />;
      case 'Organic Chemical':
        return <ScienceIcon />;
      case 'Synthetic Chemical':
        return <LocalPharmacyIcon />;
      default:
        return <InfoIcon />;
    }
  };

  return (
    <Card 
      elevation={3} 
      sx={{ 
        height: '100%', 
        display: 'flex', 
        flexDirection: 'column',
        borderTop: '4px solid',
        borderColor: getCardColor(),
        transition: 'transform 0.2s ease-in-out',
        '&:hover': {
          transform: 'translateY(-4px)',
          boxShadow: 6
        }
      }}
    >
      <CardContent sx={{ flexGrow: 1, display: 'flex', flexDirection: 'column' }}>
        <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', mb: 2 }}>
          <Typography variant="h6" component="div" sx={{ fontWeight: 'bold' }}>
            {treatment.name || 'Unnamed Treatment'}
          </Typography>
          <Chip 
            icon={getTypeIcon()} 
            label={treatment.type || 'Unspecified'} 
            size="small" 
            color={getChipColor() as any}
            variant="outlined"
          />
        </Box>

        {treatment.description && (
          <Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
            {treatment.description}
          </Typography>
        )}

        <Box sx={{ mt: 'auto' }}>
          <Grid container spacing={2}>
            {treatment.effectiveness !== undefined && (
              <Grid item xs={6}>
                <Typography variant="subtitle2" color="text.secondary">
                  Effectiveness:
                </Typography>
                <Box sx={{ display: 'flex', alignItems: 'center' }}>
                  <Box 
                    sx={{ 
                      width: '100%', 
                      bgcolor: 'grey.200', 
                      borderRadius: 1,
                      height: 8,
                      mr: 1
                    }}
                  >
                    <Box 
                      sx={{ 
                        width: `${treatment.effectiveness}%`, 
                        bgcolor: getCardColor(), 
                        borderRadius: 1,
                        height: 8
                      }} 
                    />
                  </Box>
                  <Typography variant="body2" fontWeight="bold">
                    {treatment.effectiveness}%
                  </Typography>
                </Box>
              </Grid>
            )}

            {treatment.duration && (
              <Grid item xs={6}>
                <Typography variant="subtitle2" color="text.secondary">
                  Duration:
                </Typography>
                <Typography variant="body2" sx={{ display: 'flex', alignItems: 'center' }}>
                  <AccessTimeIcon fontSize="small" sx={{ mr: 0.5, color: 'text.secondary' }} />
                  {typeof treatment.duration === 'number' 
                    ? `${treatment.duration} days` 
                    : treatment.duration}
                </Typography>
              </Grid>
            )}

            {treatment.applicationTime !== undefined && (
              <Grid item xs={6}>
                <Typography variant="subtitle2" color="text.secondary">
                  Application Time:
                </Typography>
                <Typography variant="body2" sx={{ display: 'flex', alignItems: 'center' }}>
                  <TimerIcon fontSize="small" sx={{ mr: 0.5, color: 'text.secondary' }} />
                  {`${treatment.applicationTime} minutes`}
                </Typography>
              </Grid>
            )}

            {treatment.activeSubstance && (
              <Grid item xs={6}>
                <Typography variant="subtitle2" color="text.secondary">
                  Active Substance:
                </Typography>
                <Typography variant="body2" sx={{ display: 'flex', alignItems: 'center' }}>
                  <ScienceIcon fontSize="small" sx={{ mr: 0.5, color: 'text.secondary' }} />
                  {treatment.activeSubstance}
                </Typography>
              </Grid>
            )}
          </Grid>

          {/* Advantages and Disadvantages */}
          <Box sx={{ mt: 2 }}>
            {treatment.advantages && treatment.advantages.length > 0 && (
              <Box sx={{ mb: 1 }}>
                <Typography variant="subtitle2" color="success.main" sx={{ display: 'flex', alignItems: 'center' }}>
                  <CheckCircleOutlineIcon fontSize="small" sx={{ mr: 0.5 }} />
                  Advantages:
                </Typography>
                <List dense disablePadding>
                  {treatment.advantages.map((advantage, index) => (
                    <ListItem key={index} disablePadding sx={{ py: 0.5 }}>
                      <ListItemIcon sx={{ minWidth: 24 }}>
                        <ArrowRightIcon fontSize="small" color="success" />
                      </ListItemIcon>
                      <ListItemText primary={advantage} primaryTypographyProps={{ variant: 'body2' }} />
                    </ListItem>
                  ))}
                </List>
              </Box>
            )}

            {treatment.disadvantages && treatment.disadvantages.length > 0 && (
              <Box>
                <Typography variant="subtitle2" color="error.main" sx={{ display: 'flex', alignItems: 'center' }}>
                  <ErrorOutlineIcon fontSize="small" sx={{ mr: 0.5 }} />
                  Disadvantages:
                </Typography>
                <List dense disablePadding>
                  {treatment.disadvantages.map((disadvantage, index) => (
                    <ListItem key={index} disablePadding sx={{ py: 0.5 }}>
                      <ListItemIcon sx={{ minWidth: 24 }}>
                        <ArrowRightIcon fontSize="small" color="error" />
                      </ListItemIcon>
                      <ListItemText primary={disadvantage} primaryTypographyProps={{ variant: 'body2' }} />
                    </ListItem>
                  ))}
                </List>
              </Box>
            )}
          </Box>
        </Box>
      </CardContent>
    </Card>
  );
};

const TreatmentResults: React.FC = () => {
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const varrometerState = useSelector((state: RootState) => state.varrometer);
  const [selectedTreatments, setSelectedTreatments] = useState<ImportedVarrometerTreatment[]>([]);
  
  const [isSaving, setIsSaving] = useState(false);
  const [openDialog, setOpenDialog] = useState(false);
  const [snackbar, setSnackbar] = useState<{
    open: boolean;
    message: string;
    severity: 'success' | 'error';
  }>({
    open: false,
    message: '',
    severity: 'success'
  });

  const { 
    infestationRate,
    infestationLevel,
    selectedMethod,
    miteCount,
    sampleSize,
    beekeepingType,
    timePerHive,
    hiveType,
    frames,
    geneticResistance,
    treatmentAvailable,
    assessmentDate,
    reference,
    monitoringHistory,
    colonyStrength
  } = varrometerState;
  
  const [treatments, setTreatments] = useState<Treatment[]>([]);
  
  useEffect(() => {
    const loadTreatments = async () => {
      const loadedTreatments = await loadTreatmentsFromCSV();
      const formattedTreatments = loadedTreatments.map(t => ({
        name: t.name,
        effectiveness: parseInt(t.efficacy) || 0,
        duration: parseInt(t.duration) || 0,
        relativeCost: t.costCategory === 'high' ? 25 : t.costCategory === 'medium' ? 15 : 10,
        naturalness: t.organicCompatible ? 90 : 60,
        isAvailable: true,
        temperature: {
          min: parseInt(t.temperatureMin.toString()) || 20,
          max: parseInt(t.temperatureMax.toString()) || 30
        },
      }));
      setTreatments(formattedTreatments);
    };
    
    loadTreatments();
  }, []);

  useEffect(() => {
    if (varrometerState.selectedTreatments) {
      setSelectedTreatments(varrometerState.selectedTreatments);
    }
  }, [varrometerState.selectedTreatments]);

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('en-US', {
      year: 'numeric',
      month: 'long',
      day: 'numeric'
    });
  };

  const currentDate = new Date().toLocaleDateString('en-US', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit'
  });

  const getNextMonitoringDate = () => {
    const today = new Date();
    const daysToAdd = infestationLevel === 'red' ? 15 : 30;
    const nextDate = new Date(today.setDate(today.getDate() + daysToAdd));
    return formatDate(nextDate.toISOString());
  };

  const getSeasonalAdvice = () => {
    const month = new Date().getMonth();
    if (month >= 2 && month <= 4) return 'spring';
    if (month >= 5 && month <= 7) return 'summer';
    if (month >= 8 && month <= 10) return 'autumn';
    return 'winter';
  };

  const getSeasonalTips = () => {
    const season = getSeasonalAdvice();
    const tips = {
      spring: [
        'Perform frequent monitoring during colony development',
        'Check for drone brood presence',
        'Consider biotechnical methods like drone brood removal',
        'Maintain good hive ventilation'
      ],
      summer: [
        'Monitor after honey harvest',
        'Evaluate need for emergency treatments',
        'Keep detailed temperature records',
        'Ensure sufficient hive space'
      ],
      autumn: [
        'Prepare colony for winter',
        'Apply treatments before winter cluster forms',
        'Verify food reserves',
        'Reduce hive entrances'
      ],
      winter: [
        'Minimize hive opening',
        'Monitor mite mortality at entrance',
        'Plan strategies for next season',
        'Keep hive dry and well ventilated'
      ]
    };
    return tips[season as keyof typeof tips];
  };

  type DialogType = 'temperature' | 'comparison' | 'risk' | 'lifecycle' | null;
  const [openDialogType, setOpenDialogType] = React.useState<DialogType>(null);
  
  const handleOpenDialog = (dialog: DialogType) => {
    setOpenDialogType(dialog);
  };
  
  const handleCloseDialogType = () => {
    setOpenDialogType(null);
  };

  const dialogTitles: Record<NonNullable<DialogType>, string> = {
    temperature: 'Temperature Impact on Treatment Effectiveness',
    comparison: 'Treatment Comparison',
    risk: 'Risk Levels Throughout the Year',
    lifecycle: 'Varroa Life Cycle and Treatment Vulnerability'
  };

  const dialogContent: Record<NonNullable<DialogType>, string> = {
    temperature: 'Temperature affects the effectiveness of treatments. Ideal temperatures for treatment application are between 10°C and 25°C.',
    comparison: 'Compare the effectiveness of different treatments based on their duration, cost, and naturalness.',
    risk: 'Risk levels vary throughout the year. Monitor your colony regularly to identify potential risks and take action accordingly.',
    lifecycle: 'Understanding the varroa life cycle is crucial for effective treatment. Treatments are most effective during the broodless period.'
  };

  const handleSaveTest = async () => {
    if (!auth.currentUser) {
      setSnackbar({
        open: true,
        message: 'Debes iniciar sesión para guardar el test',
        severity: 'error'
      });
      navigate('/login');
      return;
    }

    try {
      setIsSaving(true);
      const personalizedRecommendations = getPersonalizedRecommendations();
      const seasonalTips = getSeasonalTips();
      const currentSeason = getSeasonalAdvice();
      
      const testData: VarroaTest = {
        id: '',
        userId: auth.currentUser.uid,
        reference: editedReference || reference || `Test-${new Date().toISOString()}`,
        evaluationDate: Timestamp.fromDate(new Date(assessmentDate || new Date().toISOString())),
        reportGeneratedDate: Timestamp.fromDate(new Date()),

        method: MONITORING_METHODS.find(m => m.id === selectedMethod)?.name || 'Not specified',
        miteCount: miteCount || 0,
        sampleSize: sampleSize || 0,
        infestationRate: infestationRate || 0,
        status: infestationLevel || 'Not specified',

        beekeepingType: beekeepingType || 'Not specified',
        timePerHive: timePerHive || 'Not specified',
        hiveType: hiveType || 'Not specified',
        colonyStrength: getColonyStrength(frames) || 'Not specified',
        geneticResistance: geneticResistance || 'Not specified',
        hiveModel: 'Standard',
        frames: Number(frames) || 0,
        bottomBoard: 'Standard',

        treatmentApplied: selectedTreatments?.[0]?.name || 'Not specified',
        selectedTreatments: selectedTreatments?.map(treatment => ({
          name: treatment.name || 'Not specified',
          duration: treatment.duration || '0',
          effectiveness: treatment.effectiveness || 0,
          applicationTime: typeof treatment.applicationTime === 'string' ? 
            parseInt(treatment.applicationTime) || 0 : 
            treatment.applicationTime || 0,
          temperatureMin: treatment.temperatureMin || 20,
          temperatureMax: treatment.temperatureMax || 30,
          activeSubstance: treatment.activeSubstance || '',
          type: treatment.type || 'Synthetic Chemical',
          temperature: {
            min: treatment.temperatureMin || 20,
            max: treatment.temperatureMax || 30
          }
        })) || [],
        selectedBiotechnicalMethods: [],
        previousTreatment: 'None',
        treatmentAvailability: treatmentAvailable || 'Not specified',
        veterinaryProduct: 'None',
        actionTime: 'Immediate',

        beePopulation: {
          current: 10000,
          projected: [10000],
          dates: [new Date().toISOString()]
        },
        mitePopulation: {
          current: miteCount || 0,
          projected: calculateMiteProjection(miteCount || 0, infestationRate || 0),
          withTreatment: calculateTreatedMiteProjection(miteCount || 0, selectedTreatments?.[0]?.effectiveness || 0),
          dates: generateProjectionDates()
        },

        riskLevels: {
          warning: 3,
          critical: 5,
          monthlyProjections: calculateMonthlyProjections(infestationRate || 0)
        },

        temperatureImpact: {
          temperatures: selectedTreatments?.[0]?.temperatureMin && selectedTreatments?.[0]?.temperatureMax ? 
            [selectedTreatments[0].temperatureMin, selectedTreatments[0].temperatureMax] : 
            [20],
          effectiveness: [selectedTreatments?.[0]?.effectiveness || 95],
          currentTemp: 20
        },

        monitoringHistory: [{
          date: new Date(assessmentDate || new Date().toISOString()).toISOString(),
          method: MONITORING_METHODS.find(m => m.id === selectedMethod)?.name || 'Not specified',
          miteCount: miteCount || 0,
          sampleSize: sampleSize || 0,
          infestationRate: infestationRate || 0,
          infestationLevel: infestationLevel || 'Not specified',
          treatmentApplied: selectedTreatments?.[0]?.name || 'Not specified'
        }],
        nextMonitoringDate: new Date(Date.now() + (infestationLevel === 'red' ? 15 : 30) * 24 * 60 * 60 * 1000),

        seasonalAdvice: seasonalTips || ['Monitor regularly'],
        currentSeason: currentSeason || 'Not specified',
        seasonalTips: seasonalTips || ['Monitor regularly'],

        documentation: {
          treatmentGuide: 'Standard treatment guide',
          monitoringMethods: 'Standard monitoring methods'
        },
        contacts: {
          veterinarian: 'Local veterinarian',
          association: 'Local beekeeping association'
        },

        treatmentPrediction: {
          treatmentDate: new Date(),
          effectiveness: selectedTreatments?.[0]?.effectiveness || 95,
          projectedInfestationRates: calculateInfestationTimeline(infestationRate || 0, selectedTreatments?.[0]?.effectiveness || 0),
          projectedDates: generateProjectionDates()
        },

        recommendations: personalizedRecommendations.map(rec => ({
          title: rec.title || 'General Recommendation',
          description: rec.description || 'No specific details available',
          category: 'treatment',
          priority: rec.title.toLowerCase().includes('urgent') ? 'high' : 'medium'
        })) || [],

        environment: {
          temperature: 20,
          humidity: 65,
          season: currentSeason || 'Not specified',
          location: undefined
        }
      };

      await saveVarroaTest(testData, auth.currentUser.uid);
      
      setSnackbar({
        open: true,
        message: 'Test saved successfully!',
        severity: 'success'
      });
      
      dispatch(resetVarrometerState());
      navigate('/history'); 
    } catch (error) {
      console.error('Error saving test:', error);
      setSnackbar({
        open: true,
        message: 'Error saving test. Please try again.',
        severity: 'error'
      });
    } finally {
      setIsSaving(false);
    }
  };

  const calculateMiteProjection = (currentMites: number, currentRate: number): number[] => {
    return Array(6).fill(0).map((_, i) => currentMites * (1 + (0.1 * i)));
  };

  const calculateTreatedMiteProjection = (currentMites: number, effectiveness: number): number[] => {
    return Array(6).fill(0).map((_, i) => currentMites * (1 - (effectiveness/100)) * (1 + (0.05 * i)));
  };

  const calculateMonthlyProjections = (currentRate: number): number[] => {
    return Array(12).fill(0).map((_, i) => currentRate * (1 + (0.1 * i)));
  };

  const calculateInfestationProjection = (currentRate: number, effectiveness: number): number => {
    return Math.max(0, currentRate * (1 - effectiveness / 100));
  };

  const calculateInfestationTimeline = (currentRate: number, effectiveness: number): number[] => {
    return Array(6).fill(0).map((_, i) => currentRate * (1 - (effectiveness/100)) * (1 + (0.05 * i)));
  };

  const generateProjectionDates = (): string[] => {
    const dates: string[] = [];
    const currentDate = new Date();
    for (let i = 0; i < 6; i++) {
      const date = new Date(currentDate);
      date.setMonth(date.getMonth() + i);
      dates.push(date.toISOString());
    }
    return dates;
  };

  const getCurrentSeason = (): string => {
    const month = new Date().getMonth();
    if (month >= 2 && month <= 4) return 'spring';
    if (month >= 5 && month <= 7) return 'summer';
    if (month >= 8 && month <= 10) return 'autumn';
    return 'winter';
  };

  const handleCloseDialog = () => {
    setOpenDialog(false);
  };

  const handleCloseSnackbar = () => {
    setSnackbar(prev => ({ ...prev, open: false }));
  };

  const getPersonalizedRecommendations = () => {
    const recommendations = [];
    
    if (infestationRate && infestationRate > 5) {
      recommendations.push({
        title: 'Urgent Treatment Required',
        description: 'High infestation levels detected. Immediate treatment is recommended to prevent colony collapse.'
      });
    }

    if (hiveType === 'langstroth') {
      recommendations.push({
        title: 'Hive Management',
        description: 'For Langstroth hives, ensure proper ventilation between boxes and consider adding a screened bottom board for better varroa control.'
      });
    }

    if (colonyStrength === 'weak') {
      recommendations.push({
        title: 'Colony Strengthening',
        description: 'Consider combining with a stronger colony or providing supplemental feeding before treatment.'
      });
    }

    if (geneticResistance === 'varroa_tolerant') {
      recommendations.push({
        title: 'Genetic Advantage',
        description: 'Your colony shows good genetic resistance. Consider breeding from this colony to improve overall apiary resistance.'
      });
    }

    const seasonalTips = getSeasonalTips();
    recommendations.push({
      title: `Seasonal Advice (${getSeasonalAdvice()})`,
      description: seasonalTips.join('. ')
    });

    if (beekeepingType === 'organic') {
      recommendations.push({
        title: 'Organic Treatment Options',
        description: 'Consider using organic acids or biotechnical methods like drone brood removal for varroa control.'
      });
    }

    if (timePerHive === 'less_than_10min') {
      recommendations.push({
        title: 'Time Management',
        description: 'Focus on efficient monitoring methods and consider treatments that require minimal follow-up.'
      });
    }

    return recommendations;
  };

  const getBiotechnicalMethodsSection = () => {
    const methods = [
      { id: 'drone_brood_removal', name: 'Drone Brood Removal', description: 'Remove drone brood to reduce varroa population', difficulty: 'Easy', timeRequired: '30 minutes' },
      { id: 'powdered_sugar_dusting', name: 'Powdered Sugar Dusting', description: 'Dust bees with powdered sugar to dislodge varroa', difficulty: 'Medium', timeRequired: '1 hour' },
      { id: 'essential_oil_treatment', name: 'Essential Oil Treatment', description: 'Use essential oils to repel varroa', difficulty: 'Hard', timeRequired: '2 hours' },
    ];
    return (
      <Paper elevation={3} sx={{ p: 3, mb: 4 }}>
        <Typography 
          variant="h6" 
          gutterBottom 
          sx={{ 
            display: 'flex',
            alignItems: 'center',
            gap: 1,
            color: '#f2994A',
            fontWeight: 600
          }}
        >
          Available Biotechnical Methods
        </Typography>
        <Typography variant="body2" color="text.secondary" gutterBottom>
          Consider these non-chemical methods to complement your Varroa control strategy
        </Typography>
        <Grid container spacing={3}>
          {methods.map((method) => (
            <Grid item xs={12} md={4} key={method.id}>
              <Card sx={{ height: '100%' }}>
                <CardContent>
                  <Typography variant="h6" gutterBottom>
                    {method.name}
                  </Typography>
                  <Typography variant="body2" color="text.secondary" paragraph>
                    {method.description}
                  </Typography>
                  <Stack direction="row" spacing={1} flexWrap="wrap" gap={1}>
                    <Chip 
                      label={`Difficulty: ${method.difficulty}`}
                      size="small"
                      color="primary"
                    />
                    <Chip 
                      label={`Time: ${method.timeRequired}`}
                      size="small"
                      color="secondary"
                    />
                  </Stack>
                </CardContent>
              </Card>
            </Grid>
          ))}
        </Grid>
      </Paper>
    );
  };

  type CardType = 'beekeeping' | 'time' | 'hive' | 'colony' | 'genetic' | 'infestation' | 'treatment' | 'assessment' | 'frames' | 'title';

  const getCardColor = (type: CardType): string => {
    const colors: Record<CardType, string> = {
      beekeeping: '#4CAF50',
      time: '#2196F3',
      hive: '#FF9800',
      colony: '#FFC107',
      genetic: '#9C27B0',
      infestation: '#f44336',
      treatment: '#E91E63',
      assessment: '#03A9F4',
      frames: '#FF5722',
      title: '#1976d2'
    };
    return colors[type] || '#2196F3';
  };

  const getColonyStrength = (frames: number | undefined): string => {
    if (!frames) return 'Not specified';
    if (frames <= 5) return 'núcleo';
    if (frames <= 8) return 'débil';
    if (frames <= 10) return 'media';
    return 'fuerte';
  };

  const [isEditingTitle, setIsEditingTitle] = useState(false);
  const [editedReference, setEditedReference] = useState(reference);

  const handleTitleEdit = () => {
    setIsEditingTitle(true);
  };

  const handleTitleSave = () => {
    setIsEditingTitle(false);
    setSnackbar({
      open: true,
      message: 'Title updated successfully!',
      severity: 'success'
    });
  };

  const handleTitleCancel = () => {
    setIsEditingTitle(false);
    setEditedReference(reference); // Restaurar el título original
  };

  const handleTitleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setEditedReference(event.target.value);
  };

  const getRiskLevel = (level: string): number => {
    switch (level) {
      case 'green': return 25;
      case 'yellow': return 50;
      case 'red': return 75;
      default: return 50;
    }
  };

  const renderSelectedFilters = () => {
    return (
      <Paper elevation={3} sx={{ p: 3, mb: 4 }}>
        <Box sx={{ display: 'flex', alignItems: 'center', mb: 2 }}>
          <Typography 
            variant="h6" 
            sx={{ 
              display: 'flex',
              alignItems: 'center',
              gap: 1,
              color: '#f2994A',
              fontWeight: 600
            }}
          >
            <FilterListIcon sx={{ color: '#f2994A' }} />
            Colony Information
          </Typography>
        </Box>
        <Grid container spacing={2} sx={{ mt: 2 }}>
          {[
            {
              type: 'beekeeping',
              icon: <AgricultureIcon />,
              title: 'Beekeeping Type',
              value: beekeepingType
            },
            {
              type: 'time',
              icon: <AccessTimeIcon />,
              title: 'Time Available',
              value: timePerHive
            },
            {
              type: 'hive',
              icon: <HomeIcon />,
              title: 'Hive Type',
              value: hiveType
            },
            {
              type: 'colony',
              icon: <BugReportIcon />,
              title: 'Colony Strength',
              value: getColonyStrength(frames)
            },
            {
              type: 'genetic',
              icon: <ScienceIcon />,
              title: 'Genetic Resistance',
              value: geneticResistance
            },
            {
              type: 'treatment',
              icon: <LocalPharmacyIcon />,
              title: 'Treatment Available',
              value: treatmentAvailable
            },
            {
              type: 'assessment',
              icon: <CalendarTodayIcon />,
              title: 'Assessment Date',
              value: assessmentDate ? formatDate(assessmentDate) : undefined
            },
            {
              type: 'infestation',
              icon: <WarningIcon />,
              title: 'Infestation Level',
              value: infestationLevel
            },
            {
              type: 'frames',
              icon: <GridOnIcon />,
              title: 'Frames',
              value: frames?.toString() || 'Not specified'
            }
          ].map((item, index) => (
            <Grid item xs={12} sm={4} md={1.33} key={item.type}>
              <Card sx={{ 
                height: '100%',
                borderRadius: 2,
                bgcolor: 'background.paper',
                transition: 'all 0.3s ease',
                '&:hover': { 
                  transform: 'translateY(-4px)',
                  boxShadow: 3
                }
              }}>
                <CardContent sx={{
                  display: 'flex',
                  flexDirection: 'column',
                  alignItems: 'center',
                  textAlign: 'center',
                  gap: 1
                }}>
                  <Box sx={{ 
                    color: 'primary.main',
                    display: 'flex',
                    justifyContent: 'center',
                    mb: 1
                  }}>
                    {item.icon}
                  </Box>
                  <Typography variant="subtitle1" sx={{ 
                    fontWeight: 600,
                    color: 'text.primary'
                  }}>
                    {item.title}
                  </Typography>
                  <Typography variant="body1" sx={{ 
                    color: 'text.secondary',
                    fontWeight: 500
                  }}>
                    {item.value || 'Not specified'}
                  </Typography>
                </CardContent>
              </Card>
            </Grid>
          ))}
        </Grid>
      </Paper>
    );
  };

  const renderStatusCards = () => {
    return (
      <>
        <Grid item xs={12} sm={6} md={3}>
          <Card elevation={3} sx={{ 
            height: '100%', 
            bgcolor: 'info.light', 
            color: 'white',
            mx: 0
          }}>
            <CardContent>
              <Typography variant="h6" gutterBottom>
                Next Monitoring
              </Typography>
              <Typography variant="body1">
                {getNextMonitoringDate()}
              </Typography>
              <Typography variant="caption">
                Based on current infestation level
              </Typography>
            </CardContent>
          </Card>
        </Grid>
        <Grid item xs={12} sm={6} md={3}>
          <Card elevation={3} sx={{ 
            height: '100%', 
            bgcolor: 
              infestationLevel === 'green' ? 'success.light' :
              infestationLevel === 'yellow' ? 'warning.light' : 'error.light',
            color: 'white',
            mx: 0
          }}>
            <CardContent>
              <Typography variant="h6" gutterBottom>
                Current Status
              </Typography>
              <Typography variant="h4">
                {(infestationRate ?? 0).toFixed(1)}%
              </Typography>
              <Typography variant="caption">
                Infestation level {infestationLevel === 'green' ? 'low' : 
                                infestationLevel === 'yellow' ? 'medium' : 'high'}
              </Typography>
            </CardContent>
          </Card>
        </Grid>
        <Grid item xs={12} sm={6} md={3}>
          <Card elevation={3} sx={{ 
            height: '100%', 
            bgcolor: 'secondary.light', 
            color: 'white',
            mx: 0
          }}>
            <CardContent>
              <Typography variant="h6" gutterBottom>
                Colony Strength
              </Typography>
              <Typography variant="body1">
                {getColonyStrength(frames)}
              </Typography>
              <Typography variant="caption">
                Important for treatment selection
              </Typography>
            </CardContent>
          </Card>
        </Grid>
        <Grid item xs={12} sm={6} md={3}>
          <Card elevation={3} sx={{ 
            height: '100%', 
            bgcolor: 'success.light', 
            color: 'white',
            mx: 0
          }}>
            <CardContent>
              <Typography variant="h6" gutterBottom>
                Beekeeping Type
              </Typography>
              <Typography variant="body1">
                {beekeepingType?.replace('_', ' ') || 'Not specified'}
              </Typography>
              <Typography variant="caption">
                {beekeepingType === 'organic' ? 'Use only organic treatments' : 'All treatments available'}
              </Typography>
            </CardContent>
          </Card>
        </Grid>
      </>
    );
  };

  // Helper function to get the recommended action based on infestation level
  const getRecommendedAction = () => {
    if (infestationRate <= 3) {
      return {
        text: 'No action required',
        color: '#4caf50', // green
        bgColor: '#E8F5E9' // light green background
      };
    } else if (infestationRate <= 5) {
      return {
        text: 'Monitor closely',
        color: '#ff9800', // orange
        bgColor: '#FFF3E0' // light orange background
      };
    } else {
      return {
        text: 'Immediate treatment required',
        color: '#e53935', // red
        bgColor: '#FFEBEE' // light red background
      };
    }
  };

  // Helper function to get the risk level text
  const getRiskLevelText = () => {
    if (infestationRate <= 3) {
      return 'Safe';
    } else if (infestationRate <= 5) {
      return 'Warning';
    } else {
      return 'High Risk';
    }
  };

  const [showCriticalInfo, setShowCriticalInfo] = useState(true);

  const renderCriticalInformationPanel = () => {
    // Determine infestation level based on rate
    const getInfestationLevel = () => {
      if (infestationRate <= 3) {
        return {
          text: 'Safe',
          color: '#4caf50' // green
        };
      } else if (infestationRate <= 5) {
        return {
          text: 'Warning',
          color: '#ff9800' // orange
        };
      } else {
        return {
          text: 'High Risk',
          color: '#e53935' // red
        };
      }
    };

    const infestationLevel = getInfestationLevel();
    
    // Determine recommended action based on infestation level
    const recommendedAction = getRecommendedAction();

    return (
      <Paper 
        elevation={3} 
        sx={{ 
          p: 0, 
          mb: 4, 
          border: '1px solid #f0f0f0',
          borderRadius: 2,
          overflow: 'hidden'
        }}
      >
        <Box sx={{ p: 2, display: 'flex', justifyContent: 'space-between', alignItems: 'center', borderBottom: '1px solid #f0f0f0' }}>
          <Box sx={{ display: 'flex', alignItems: 'center' }}>
            <Box component="span" sx={{ color: 'error.main', mr: 1, display: 'flex', fontSize: '1rem' }}>
              ▲
            </Box>
            <Typography variant="subtitle1" sx={{ fontWeight: 500 }}>
              Critical Information
            </Typography>
          </Box>
          <IconButton 
            onClick={() => setShowCriticalInfo(!showCriticalInfo)}
            size="small"
          >
            {showCriticalInfo ? <VisibilityOffIcon fontSize="small" /> : <VisibilityIcon fontSize="small" />}
          </IconButton>
        </Box>

        {showCriticalInfo && (
          <Box sx={{ p: 2 }}>
            <Typography variant="caption" color="text.secondary" sx={{ display: 'block', mb: 2 }}>
              Key metrics and recommended actions based on your colony's current state
            </Typography>
            
            <Grid container spacing={3}>
              {/* Left column - Key metrics */}
              <Grid item xs={12} md={6}>
                <Box sx={{ mb: 2 }}>
                  <Typography variant="caption" color="text.secondary" sx={{ display: 'block', mb: 0.5 }}>
                    Infestation Level
                  </Typography>
                  <Typography 
                    variant="body1" 
                    sx={{ 
                      fontWeight: 500, 
                      color: infestationLevel.color,
                    }}
                  >
                    {infestationLevel.text}
                  </Typography>
                </Box>

                <Box sx={{ mb: 2 }}>
                  <Typography variant="caption" color="text.secondary" sx={{ display: 'block', mb: 0.5 }}>
                    Infestation Rate
                  </Typography>
                  <Typography variant="body1" sx={{ fontWeight: 500 }}>
                    {infestationRate?.toFixed(1)}%
                  </Typography>
                </Box>

                <Box sx={{ mb: 2 }}>
                  <Typography variant="caption" color="text.secondary" sx={{ display: 'block', mb: 0.5 }}>
                    Colony Strength
                  </Typography>
                  <Typography variant="body1" sx={{ fontWeight: 500 }}>
                    {getColonyStrength(frames)}
                  </Typography>
                </Box>

                <Box sx={{ mb: 2 }}>
                  <Typography variant="caption" color="text.secondary" sx={{ display: 'block', mb: 0.5 }}>
                    Next Monitoring
                  </Typography>
                  <Box sx={{ display: 'flex', alignItems: 'center' }}>
                    <Box component="span" sx={{ display: 'inline-block', mr: 1, fontSize: '0.875rem' }}>☐</Box>
                    <Typography variant="body1" sx={{ fontWeight: 500 }}>
                      {getNextMonitoringDate()}
                    </Typography>
                  </Box>
                </Box>

                {/* Recommended Action */}
                <Box 
                  sx={{ 
                    mt: 2, 
                    p: 2, 
                    bgcolor: alpha(recommendedAction.color, 0.08),
                    borderRadius: 1,
                  }}
                >
                  <Box sx={{ display: 'flex', alignItems: 'flex-start' }}>
                    <Box sx={{ mr: 1, mt: 0.5, color: recommendedAction.color, display: 'flex', fontSize: '0.875rem' }}>
                      ●
                    </Box>
                    <Box>
                      <Typography 
                        variant="caption" 
                        sx={{ 
                          color: 'text.secondary',
                          display: 'block',
                          mb: 0.5
                        }}
                      >
                        Recommended Action
                      </Typography>
                      <Typography variant="body2" sx={{ color: 'text.primary' }}>
                        {recommendedAction.text}
                      </Typography>
                    </Box>
                  </Box>
                </Box>
              </Grid>

              {/* Right column - Visual indicator */}
              <Grid item xs={12} md={6}>
                <Box sx={{ height: '100%', display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center' }}>
                  <Typography 
                    variant="h4" 
                    align="center" 
                    sx={{ 
                      fontWeight: 500,
                      color: infestationLevel.color,
                      mb: 3
                    }}
                  >
                    {infestationRate?.toFixed(1)}%
                  </Typography>
                  
                  <Box sx={{ 
                    width: '100%', 
                    position: 'relative',
                    height: '180px',
                    mb: 2
                  }}>
                    {/* Percentage labels - left side */}
                    <Box sx={{
                      position: 'absolute',
                      left: '30%',
                      top: 0,
                      bottom: 0,
                      display: 'flex',
                      flexDirection: 'column',
                      justifyContent: 'space-between',
                      py: 1,
                      zIndex: 2
                    }}>
                      <Typography variant="caption" sx={{ color: '#e53935' }}>15%</Typography>
                      <Typography variant="caption" sx={{ color: '#e53935' }}>10%</Typography>
                      <Typography variant="caption" sx={{ color: '#e53935' }}>5%</Typography>
                      <Typography variant="caption" sx={{ color: '#4caf50' }}>3%</Typography>
                      <Typography variant="caption" sx={{ color: '#e53935' }}>0%</Typography>
                    </Box>
                    
                    {/* Thermometer container - centered */}
                    <Box sx={{
                      width: '40px',
                      height: '100%',
                      position: 'absolute',
                      left: '50%',
                      transform: 'translateX(-50%)'
                    }}>
                      {/* Background gray area */}
                      <Box sx={{
                        position: 'absolute',
                        left: 0,
                        right: 0,
                        top: 0,
                        bottom: 0,
                        bgcolor: '#f5f5f5',
                        borderRadius: 1,
                        zIndex: 1
                      }} />
                      
                      {/* Bar representing infestation level with dynamic color */}
                      <Box sx={{
                        position: 'absolute',
                        left: 0,
                        right: 0,
                        bottom: 0,
                        height: `${Math.min(100, (infestationRate ?? 0) * (100/15))}%`,
                        bgcolor: infestationLevel.color,
                        borderRadius: '0 0 4px 4px',
                        zIndex: 1
                      }} />
                    </Box>
                  </Box>
                  
                  {/* Legend */}
                  <Box sx={{ 
                    display: 'flex', 
                    width: '100%', 
                    justifyContent: 'space-between',
                    px: 1
                  }}>
                    <Box sx={{ display: 'flex', alignItems: 'center' }}>
                      <Box sx={{ width: 8, height: 8, borderRadius: '50%', bgcolor: '#4caf50', mr: 0.5 }} />
                      <Typography variant="caption" sx={{ color: '#4caf50' }}>Safe (0-3%)</Typography>
                    </Box>
                    <Box sx={{ display: 'flex', alignItems: 'center' }}>
                      <Box sx={{ width: 8, height: 8, borderRadius: '50%', bgcolor: '#ff9800', mr: 0.5 }} />
                      <Typography variant="caption" sx={{ color: '#ff9800' }}>Warning (3-5%)</Typography>
                    </Box>
                    <Box sx={{ display: 'flex', alignItems: 'center' }}>
                      <Box sx={{ width: 8, height: 8, borderRadius: '50%', bgcolor: '#e53935', mr: 0.5 }} />
                      <Typography variant="caption" sx={{ color: '#e53935' }}>High Risk (5%+)</Typography>
                    </Box>
                  </Box>
                </Box>
              </Grid>
            </Grid>
          </Box>
        )}
      </Paper>
    );
  };

  return (
    <Box sx={{ p: 3, pb: 12 }}>
      <Box
        sx={{
          background: 'linear-gradient(45deg, #FFA726 30%, #FB8C00 90%)',
          color: 'white',
          py: 4,
          px: 2,
          mb: 4,
          textAlign: 'center'
        }}
      >
        <Typography variant="h4" component="h2" gutterBottom sx={{ color: 'white' }}>
          Treatment Report
        </Typography>
        <Typography variant="body1">
          Evaluation Date: {assessmentDate ? formatDate(assessmentDate) : 'Not specified'}
        </Typography>
        <Typography variant="body1">
          Report generated on: {currentDate}
        </Typography>
      </Box>

      {/* Add the Critical Information Panel at the beginning of the report */}
      {renderCriticalInformationPanel()}

      {reference && (
        <Paper elevation={3} sx={{ p: 3, mb: 4 }}>
          <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', mb: 2 }}>
            <Typography variant="h6" sx={{ color: '#f2994A', fontWeight: 600 }}>
              Reference Information
            </Typography>
            {!isEditingTitle && (
              <IconButton 
                onClick={handleTitleEdit}
                size="small"
                sx={{ color: '#f2994A' }}
              >
                <EditIcon />
              </IconButton>
            )}
          </Box>
          {isEditingTitle ? (
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
              <TextField
                value={editedReference}
                onChange={handleTitleChange}
                variant="standard"
                fullWidth
                autoFocus
                placeholder="Enter report title"
                sx={{
                  '& .MuiInput-underline:before': {
                    borderBottomColor: '#f0b400',
                  },
                  '& .MuiInput-underline:after': {
                    borderBottomColor: '#f0b400',
                  },
                }}
              />
              <Box sx={{ display: 'flex', gap: 1 }}>
                <Button
                  variant="contained"
                  onClick={handleTitleSave}
                  size="small"
                  sx={{
                    bgcolor: '#f0b400',
                    '&:hover': {
                      bgcolor: '#d69600',
                    },
                  }}
                >
                  Save
                </Button>
                <Button
                  variant="outlined"
                  onClick={handleTitleCancel}
                  size="small"
                  sx={{
                    color: '#f0b400',
                    borderColor: '#f0b400',
                    '&:hover': {
                      borderColor: '#d69600',
                      color: '#d69600',
                    },
                  }}
                >
                  Cancel
                </Button>
              </Box>
            </Box>
          ) : (
            <Typography 
              variant="h5" 
              sx={{ 
                fontWeight: 600,
                textAlign: 'center',
                mt: 2
              }}
            >
              {editedReference}
            </Typography>
          )}
        </Paper>
      )}

      {renderSelectedFilters()}

      <Box sx={{ mb: 4, mx: 0 }}>
        <Grid container spacing={2}>
          {renderStatusCards()}
        </Grid>
      </Box>

      <Paper elevation={3} sx={{ p: 3, mb: 4 }}>
        <Typography 
          variant="h6" 
          gutterBottom 
          sx={{ 
            display: 'flex',
            alignItems: 'center',
            gap: 1,
            color: '#F2994A',
            fontWeight: 600
          }}
        >
          Current Infestation Status
        </Typography>
        
        <Box sx={{ width: '100%', mb: 4 }}>
          <Typography variant="subtitle1" gutterBottom>
            Varroa Infestation Level
          </Typography>
          
          <Box sx={{ 
            position: 'relative', 
            width: '100%', 
            height: '60px',
            bgcolor: 'grey.200',
            borderRadius: 2,
            mb: 2
          }}>
            <Box sx={{
              position: 'absolute',
              top: 0,
              left: 0,
              right: 0,
              bottom: 0,
              display: 'flex',
              borderRadius: 2,
              overflow: 'hidden'
            }}>
              <Box sx={{ flex: 3, bgcolor: 'success.light' }} /> 
              <Box sx={{ flex: 2, bgcolor: 'warning.light' }} /> 
              <Box sx={{ flex: 10, bgcolor: 'error.light' }} /> 
            </Box>
            
            <Box sx={{
              position: 'absolute',
              left: `${Math.min((infestationRate ?? 0) * (100/15), 100)}%`,
              top: '50%',
              transform: 'translate(-50%, -50%)',
              width: '20px',
              height: '40px',
              bgcolor: infestationRate && infestationRate > 5 ? 'error.main' : 
                      infestationRate && infestationRate > 3 ? 'warning.main' : 'success.main',
              borderRadius: '10px',
              border: '2px solid white',
              boxShadow: 2,
              zIndex: 1
            }} />

            <Box sx={{
              position: 'absolute',
              top: '100%',
              left: 0,
              right: 0,
              display: 'flex',
              justifyContent: 'space-between',
              px: 1,
              mt: 1
            }}>
              <Typography variant="caption" color="text.secondary">0%</Typography>
              <Typography variant="caption" color="text.secondary">15%</Typography>
            </Box>
          </Box>

          <Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 3 }}>
            <Box sx={{ display: 'flex', alignItems: 'center' }}>
              <Box sx={{ width: 12, height: 12, borderRadius: '50%', bgcolor: 'success.light', mr: 1 }} />
              <Typography variant="caption" color="text.secondary">Safe (0-3%)</Typography>
            </Box>
            <Box sx={{ display: 'flex', alignItems: 'center' }}>
              <Box sx={{ width: 12, height: 12, borderRadius: '50%', bgcolor: 'warning.light', mr: 1 }} />
              <Typography variant="caption" color="text.secondary">Warning (3-5%)</Typography>
            </Box>
            <Box sx={{ display: 'flex', alignItems: 'center' }}>
              <Box sx={{ width: 12, height: 12, borderRadius: '50%', bgcolor: 'error.light', mr: 1 }} />
              <Typography variant="caption" color="text.secondary">High Risk (5%+)</Typography>
            </Box>
          </Box>

          <Grid container spacing={3}>
            <Grid item xs={12} sm={6}>
              <Typography variant="body2" color="text.secondary">
                Assessment Date:
              </Typography>
              <Typography variant="body1">
                {assessmentDate ? formatDate(assessmentDate) : 'Not specified'}
              </Typography>
            </Grid>
            <Grid item xs={12} sm={6}>
              <Typography variant="body2" color="text.secondary">
                Monitoring Method:
              </Typography>
              <Typography variant="body1">
                {MONITORING_METHODS.find(m => m.id === selectedMethod)?.name || 'Not specified'}
              </Typography>
            </Grid>
            <Grid item xs={12} sm={6}>
              <Typography variant="body2" color="text.secondary">
                Mite Count:
              </Typography>
              <Typography variant="body1">
                {miteCount} mites in {sampleSize} bees
              </Typography>
            </Grid>
            <Grid item xs={12} sm={6}>
              <Typography variant="body2" color="text.secondary">
                Infestation Rate:
              </Typography>
              <Typography variant="body1" color="error.main" sx={{ fontWeight: 'bold', fontSize: '1.2rem' }}>
                {(infestationRate ?? 0).toFixed(1)}%
              </Typography>
            </Grid>
          </Grid>
        </Box>
      </Paper>

      {monitoringHistory.length > 0 && (
        <Paper elevation={3} sx={{ p: 3, mb: 4 }}>
          <Typography 
            variant="h6" 
            gutterBottom 
            sx={{ 
              display: 'flex',
              alignItems: 'center',
              gap: 1,
              color: '#F2994A',
              fontWeight: 600
            }}
          >
            Monitoring History
          </Typography>
          <TableContainer>
            <Table size="small">
              <TableHead>
                <TableRow>
                  <TableCell>Date</TableCell>
                  <TableCell>Method</TableCell>
                  <TableCell align="right">Mite Count</TableCell>
                  <TableCell align="right">Sample Size</TableCell>
                  <TableCell align="right">Infestation Rate</TableCell>
                  <TableCell>Status</TableCell>
                  <TableCell>Treatment Applied</TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {monitoringHistory.map((record: MonitoringRecord, index) => (
                  <TableRow key={index}>
                    <TableCell>{formatDate(record.date)}</TableCell>
                    <TableCell>{MONITORING_METHODS.find(m => m.id === record.method)?.name || 'Not specified'}</TableCell>
                    <TableCell align="right">{record.miteCount}</TableCell>
                    <TableCell align="right">{record.sampleSize}</TableCell>
                    <TableCell align="right">{record.infestationRate.toFixed(1)}%</TableCell>
                    <TableCell>
                      <Chip 
                        label={record.infestationLevel}
                        color={
                          record.infestationLevel === 'green' ? 'success' :
                          record.infestationLevel === 'yellow' ? 'warning' :
                          'error'
                        }
                        size="small"
                      />
                    </TableCell>
                    <TableCell>{record.treatmentApplied ?? '-'}</TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </TableContainer>
        </Paper>
      )}

      <Paper elevation={3} sx={{ p: 3, mb: 4 }}>
        <Typography 
          variant="h6" 
          gutterBottom 
          sx={{ 
            display: 'flex',
            alignItems: 'center',
            gap: 1,
            color: '#F2994A',
            fontWeight: 600
          }}
        >
          Population Growth Analysis
        </Typography>
        
        <Grid container spacing={3}>
          <Grid item xs={12}>
            <VarroaPopulationCharts
              selectedTreatment={selectedTreatments[0]}
              assessmentDate={assessmentDate || new Date().toISOString()}
              infestationRate={infestationRate || 0}
            />
          </Grid>
        </Grid>
      </Paper>

      <Paper elevation={3} sx={{ p: 3, mb: 4 }}>
        <Typography 
          variant="h6" 
          gutterBottom 
          sx={{ 
            display: 'flex',
            alignItems: 'center',
            gap: 1,
            color: '#F2994A',
            fontWeight: 600
          }}
        >
          <BugReportIcon /> Modelo Predictivo de Crecimiento de Varroa
        </Typography>
        
        <Grid container spacing={3}>
          <Grid item xs={12}>
            <VarroaPredictiveChart
              numAcaros={miteCount || 0}
              numAbejas={sampleSize || 0}
              fechaMuestra={new Date(assessmentDate || new Date().toISOString())}
              tratamientos={selectedTreatments.map(treatment => ({
                fecha: new Date(new Date().getTime() + 7 * 24 * 60 * 60 * 1000), // 7 días después de hoy
                eficiencia: treatment.effectiveness || 0,
                nombre: treatment.name
              }))}
            />
          </Grid>
        </Grid>
      </Paper>

      <Paper elevation={3} sx={{ p: 3, mb: 4 }}>
        <Typography 
          variant="h6" 
          gutterBottom 
          sx={{ 
            display: 'flex',
            alignItems: 'center',
            gap: 1,
            color: '#F2994A',
            fontWeight: 600
          }}
        >
          Treatment Analysis
        </Typography>

        <Grid container spacing={3}>
          <Grid item xs={12}>
            <AdditionalCharts
              type="temperature"
              selectedTreatment={selectedTreatments[0]}
              temperature={20}
              infestationRate={infestationRate || 0}
              availableTreatments={treatments.map(t => ({
                name: t.name,
                effectiveness: t.effectiveness,
                duration: t.duration,
                cost: t.relativeCost,
                naturalness: t.naturalness,
                isRecommended: selectedTreatments.some(st => st.name === t.name),
                temperature: t.temperature
              }))}
            />
          </Grid>

          <Grid item xs={12}>
            <AdditionalCharts
              type="comparison"
              selectedTreatment={selectedTreatments[0]}
              temperature={20}
              infestationRate={infestationRate || 0}
              availableTreatments={treatments
                .filter((t: Treatment) => t.isAvailable)
                .map((t: Treatment) => ({
                  name: t.name,
                  effectiveness: t.effectiveness,
                  duration: t.duration,
                  cost: t.relativeCost,
                  naturalness: t.naturalness,
                  isRecommended: selectedTreatments.some(st => st.name === t.name),
                  temperature: t.temperature
                }))}
            />
          </Grid>

          <Grid item xs={12}>
            <AdditionalCharts
              type="risk"
              selectedTreatment={selectedTreatments[0]}
              temperature={20}
              infestationRate={infestationRate || 0}
              availableTreatments={treatments.map(t => ({
                name: t.name,
                effectiveness: t.effectiveness,
                duration: t.duration,
                cost: t.relativeCost,
                naturalness: t.naturalness,
                isRecommended: selectedTreatments.some(st => st.name === t.name),
                temperature: t.temperature
              }))}
            />
          </Grid>

          <Grid item xs={12}>
            <AdditionalCharts
              type="lifecycle"
              selectedTreatment={selectedTreatments[0]}
              temperature={20}
              infestationRate={infestationRate || 0}
              availableTreatments={treatments.map(t => ({
                name: t.name,
                effectiveness: t.effectiveness,
                duration: t.duration,
                cost: t.relativeCost,
                naturalness: t.naturalness,
                isRecommended: selectedTreatments.some(st => st.name === t.name),
                temperature: t.temperature
              }))}
            />
          </Grid>
        </Grid>
      </Paper>

      <Paper elevation={3} sx={{ p: 3, mb: 4 }}>
        <Typography 
          variant="h6" 
          gutterBottom 
          sx={{ 
            display: 'flex',
            alignItems: 'center',
            gap: 1,
            color: '#F2994A',
            fontWeight: 600
          }}
        >
          Recommended Treatments ({selectedTreatments.length})
        </Typography>
        <Stack spacing={3}>
          {(() => {
            // Group treatments by type
            const nonChemicalTreatments = selectedTreatments.filter(
              t => t.type === 'Mechanical methods' || t.type === 'Bio-technical methods'
            );
            
            const chemicalTreatments = selectedTreatments.filter(
              t => t.type === 'Synthetic Chemical' || t.type === 'Organic Chemical'
            );

            const unspecifiedTreatments = selectedTreatments.filter(
              t => t.type === undefined || t.type === null
            );

            return (
              <>
                {/* Non-Chemical Treatments */}
                {nonChemicalTreatments.length > 0 && (
                  <Box sx={{ mb: 4 }}>
                    <Paper 
                      elevation={0} 
                      sx={{ 
                        p: 2, 
                        mb: 2, 
                        bgcolor: alpha('#2196f3', 0.1),
                        borderRadius: '8px 8px 0 0',
                        borderLeft: '4px solid',
                        borderColor: 'info.main'
                      }}
                    >
                      <Typography variant="h6" color="primary" gutterBottom sx={{ display: 'flex', alignItems: 'center', color: 'info.main' }}>
                        <BeehiveIcon sx={{ mr: 1 }} />
                        Non-Chemical Control Methods
                      </Typography>
                      <Typography variant="body2" sx={{ mt: 1, color: 'text.secondary' }}>
                        These methods focus on mechanical and biological approaches to control Varroa mites without chemical substances.
                      </Typography>
                    </Paper>
                    
                    <Grid container spacing={2}>
                      {nonChemicalTreatments.map((treatment, index) => (
                        <Grid item xs={12} sm={6} md={4} key={`non-chemical-${index}`}>
                          <TreatmentCard treatment={treatment} />
                        </Grid>
                      ))}
                    </Grid>
                  </Box>
                )}

                {/* Chemical Methods Section */}
                {chemicalTreatments.length > 0 && (
                  <Box sx={{ mb: 4 }}>
                    <Paper 
                      elevation={0} 
                      sx={{ 
                        p: 2, 
                        mb: 2, 
                        bgcolor: alpha('#f44336', 0.1),
                        borderRadius: '8px 8px 0 0',
                        borderLeft: '4px solid',
                        borderColor: 'error.main'
                      }}
                    >
                      <Typography variant="h6" color="primary" gutterBottom sx={{ display: 'flex', alignItems: 'center', color: 'error.main' }}>
                        <LocalPharmacyIcon sx={{ mr: 1 }} />
                        Chemical Control Methods
                      </Typography>
                      <Typography variant="body2" sx={{ mt: 1, color: 'text.secondary' }}>
                        These methods use chemical substances (organic or synthetic) to effectively eliminate Varroa mites.
                      </Typography>
                    </Paper>
                    
                    <Grid container spacing={2}>
                      {chemicalTreatments.map((treatment, index) => (
                        <Grid item xs={12} sm={6} md={4} key={`chemical-${index}`}>
                          <TreatmentCard treatment={treatment} />
                        </Grid>
                      ))}
                    </Grid>
                  </Box>
                )}

                {/* Unspecified Type Treatments */}
                {unspecifiedTreatments.length > 0 && (
                  <Box sx={{ mb: 4 }}>
                    <Paper 
                      elevation={0} 
                      sx={{ 
                        p: 2, 
                        mb: 2, 
                        bgcolor: alpha('#9e9e9e', 0.1),
                        borderRadius: '8px 8px 0 0',
                        borderLeft: '4px solid',
                        borderColor: 'grey.500'
                      }}
                    >
                      <Typography variant="h6" sx={{ display: 'flex', alignItems: 'center', color: 'grey.700' }}>
                        <InfoIcon sx={{ mr: 1 }} />
                        Other Treatment Methods
                      </Typography>
                      <Typography variant="body2" sx={{ mt: 1, color: 'text.secondary' }}>
                        Additional treatment methods that may be useful in your Varroa mite management strategy.
                      </Typography>
                    </Paper>
                    
                    <Grid container spacing={2}>
                      {unspecifiedTreatments.map((treatment, index) => (
                        <Grid item xs={12} sm={6} md={4} key={`unspecified-${index}`}>
                          <TreatmentCard treatment={treatment} />
                        </Grid>
                      ))}
                    </Grid>
                  </Box>
                )}
              </>
            );
          })()}
        </Stack>
      </Paper>

      <Paper elevation={3} sx={{ p: 3, mb: 4 }}>
        <Typography 
          variant="h6" 
          gutterBottom 
          sx={{ 
            display: 'flex',
            alignItems: 'center',
            gap: 1,
            color: '#F2994A',
            fontWeight: 600
          }}
        >
          Treatment Categories
        </Typography>
        
        <Grid container spacing={2}>
          {/* Non-Chemical Control Section */}
          <Grid item xs={12}>
            <Paper elevation={3} sx={{ p: 3, mb: 4 }}>
              <Typography 
                variant="h6" 
                gutterBottom 
                sx={{ 
                  display: 'flex',
                  alignItems: 'center',
                  gap: 1,
                  color: '#F2994A',
                  fontWeight: 600
                }}
              >
                <BeehiveIcon sx={{ mr: 1 }} />
                Non-Chemical Control
              </Typography>
              <Typography variant="body2" color="text.secondary" gutterBottom>
                Consider these non-chemical methods to complement your Varroa control strategy
              </Typography>
              <Grid container spacing={2}>
                <Grid item xs={12} md={6}>
                  <Paper elevation={1} sx={{ p: 2, bgcolor: alpha('#4caf50', 0.05), height: '100%' }}>
                    <Typography variant="subtitle1" sx={{ fontWeight: 'bold', color: 'success.dark' }}>
                      Mechanical Methods
                    </Typography>
                    <Typography variant="body2">
                      Physical removal of mites without chemicals. Effective for low infestation levels.
                    </Typography>
                  </Paper>
                </Grid>
                <Grid item xs={12} md={6}>
                  <Paper elevation={1} sx={{ p: 2, bgcolor: alpha('#2196f3', 0.05), height: '100%' }}>
                    <Typography variant="subtitle1" sx={{ fontWeight: 'bold', color: 'info.dark' }}>
                      Bio-Technical Methods
                    </Typography>
                    <Typography variant="body2">
                      Manipulating bee biology to control mites. Creates broodless periods to expose mites.
                    </Typography>
                  </Paper>
                </Grid>
              </Grid>
            </Paper>
          </Grid>
          
          {/* Chemical Methods Section */}
          <Grid item xs={12}>
            <Paper elevation={3} sx={{ p: 3, mb: 4 }}>
              <Typography 
                variant="h6" 
                gutterBottom 
                sx={{ 
                  display: 'flex',
                  alignItems: 'center',
                  gap: 1,
                  color: '#F2994A',
                  fontWeight: 600
                }}
              >
                <LocalPharmacyIcon sx={{ mr: 1 }} />
                Chemical Methods
              </Typography>
              <Typography variant="body2" color="text.secondary" gutterBottom>
                Consider these chemical methods to effectively eliminate Varroa mites
              </Typography>
              <Grid container spacing={2}>
                <Grid item xs={12} md={6}>
                  <Paper elevation={1} sx={{ p: 2, bgcolor: alpha('#8bc34a', 0.05), height: '100%' }}>
                    <Typography variant="subtitle1" sx={{ fontWeight: 'bold', color: 'success.dark' }}>
                      Veterinary Products (Organic)
                    </Typography>
                    <Typography variant="body2">
                      Based on natural substances. Compatible with organic beekeeping.
                    </Typography>
                  </Paper>
                </Grid>
                <Grid item xs={12} md={6}>
                  <Paper elevation={1} sx={{ p: 2, bgcolor: alpha('#f44336', 0.05), height: '100%' }}>
                    <Typography variant="subtitle1" sx={{ fontWeight: 'bold', color: 'error.dark' }}>
                      Veterinary Products (Synthetic)
                    </Typography>
                    <Typography variant="body2">
                      Highly effective synthetic chemicals. May have residue concerns.
                    </Typography>
                  </Paper>
                </Grid>
              </Grid>
            </Paper>
          </Grid>
          
          {/* Combination Strategy Section */}
          <Grid item xs={12}>
            <Paper elevation={3} sx={{ p: 3, mt: 4, bgcolor: alpha('#673ab7', 0.05), border: '1px dashed #673ab7' }}>
              <Typography variant="h6" sx={{ fontWeight: 'bold', color: '#673ab7' }}>
                <InfoIcon sx={{ mr: 1, verticalAlign: 'middle' }} />
                Combination Strategy
              </Typography>
              <Typography variant="body1" paragraph>
                For optimal results, consider combining methods:
              </Typography>
              <Box sx={{ pl: 2 }}>
                <Typography variant="body2" paragraph sx={{ display: 'flex', alignItems: 'center' }}>
                  <ArrowRightIcon color="primary" sx={{ mr: 1 }} />
                  Use bio-technical methods (queen caging, brood removal) to create a broodless period
                </Typography>
                <Typography variant="body2" paragraph sx={{ display: 'flex', alignItems: 'center' }}>
                  <ArrowRightIcon color="primary" sx={{ mr: 1 }} />
                  Then apply chemical treatments when mites are exposed (not hiding in capped brood)
                </Typography>
                <Typography variant="body2" paragraph sx={{ display: 'flex', alignItems: 'center' }}>
                  <ArrowRightIcon color="primary" sx={{ mr: 1 }} />
                  This combination significantly increases treatment effectiveness
                </Typography>
              </Box>
            </Paper>
          </Grid>
        </Grid>
      </Paper>

      {getBiotechnicalMethodsSection()}

      <Paper elevation={3} sx={{ p: 3, mb: 4 }}>
        <Typography 
          variant="h6" 
          gutterBottom 
          sx={{ 
            display: 'flex',
            alignItems: 'center',
            gap: 1,
            color: '#F2994A',
            fontWeight: 600
          }}
        >
          <ScienceIcon />
          Treatment Combination Strategy
        </Typography>
        
        <Box sx={{ mt: 3, mb: 4 }}>
          <Grid container spacing={2}>
            {/* Left column: Bio-technical methods */}
            <Grid item xs={12} md={5}>
              <Paper 
                elevation={2} 
                sx={{ 
                  p: 2, 
                  height: '100%', 
                  bgcolor: alpha('#2196f3', 0.05),
                  border: '1px solid',
                  borderColor: 'info.light'
                }}
              >
                <Typography variant="h6" color="primary" gutterBottom>
                  <BeehiveIcon sx={{ mr: 1 }} />
                  Bio-Technical Methods
                </Typography>
                
                <Box sx={{ display: 'flex', flexDirection: 'column', gap: 1 }}>
                  <Paper sx={{ p: 1.5, bgcolor: 'background.paper' }}>
                    <Typography variant="subtitle2" sx={{ fontWeight: 'bold', color: 'info.dark' }}>
                      Queen Caging
                    </Typography>
                    <Typography variant="body2">
                      Confines the queen to prevent egg-laying
                    </Typography>
                  </Paper>
                  
                  <Paper sx={{ p: 1.5, bgcolor: 'background.paper' }}>
                    <Typography variant="subtitle2" sx={{ fontWeight: 'bold', color: 'info.dark' }}>
                      Brood Removal
                    </Typography>
                    <Typography variant="body2">
                      Removes capped brood where mites hide
                    </Typography>
                  </Paper>
                  
                  <Paper sx={{ p: 1.5, bgcolor: 'background.paper' }}>
                    <Typography variant="subtitle2" sx={{ fontWeight: 'bold', color: 'info.dark' }}>
                      Drone Brood Trapping
                    </Typography>
                    <Typography variant="body2">
                      Removes drone brood preferred by mites
                    </Typography>
                  </Paper>
                </Box>
                
                <Box sx={{ mt: 2, p: 1.5, bgcolor: alpha('#2196f3', 0.1), borderRadius: 1 }}>
                  <Typography variant="subtitle2" sx={{ fontWeight: 'bold', color: 'info.dark' }}>
                    Result:
                  </Typography>
                  <Typography variant="body2">
                    Creates a broodless period in the colony
                  </Typography>
                </Box>
              </Paper>
            </Grid>
            
            {/* Middle column: Arrow and explanation */}
            <Grid item xs={12} md={2} sx={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <Box sx={{ display: 'flex', flexDirection: 'column', alignItems: 'center', width: '100%' }}>
                <Typography 
                  variant="h4" 
                  sx={{ 
                    color: 'primary.main',
                    transform: { xs: 'rotate(90deg)', md: 'rotate(0)' },
                    my: { xs: 2, md: 0 }
                  }}
                >
                  →
                </Typography>
                <Paper 
                  elevation={0} 
                  sx={{ 
                    p: 1.5, 
                    bgcolor: alpha('#673ab7', 0.1), 
                    width: '100%',
                    textAlign: 'center',
                    borderRadius: 2,
                    mt: { xs: 0, md: 2 }
                  }}
                >
                  <Typography variant="body2" sx={{ fontWeight: 'bold' }}>
                    THEN
                  </Typography>
                </Paper>
                <Typography 
                  variant="h4" 
                  sx={{ 
                    color: 'primary.main',
                    transform: { xs: 'rotate(90deg)', md: 'rotate(0)' },
                    my: { xs: 2, md: 0 }
                  }}
                >
                  →
                </Typography>
              </Box>
            </Grid>
            
            {/* Right column: Chemical treatments */}
            <Grid item xs={12} md={5}>
              <Paper 
                elevation={2} 
                sx={{ 
                  p: 2, 
                  height: '100%', 
                  bgcolor: alpha('#f44336', 0.05),
                  border: '1px solid',
                  borderColor: 'error.light'
                }}
              >
                <Typography variant="h6" color="primary" gutterBottom>
                  <LocalPharmacyIcon sx={{ mr: 1 }} />
                  Chemical Treatments
                </Typography>
                
                <Box sx={{ display: 'flex', flexDirection: 'column', gap: 1 }}>
                  <Paper sx={{ p: 1.5, bgcolor: 'background.paper' }}>
                    <Typography variant="subtitle2" sx={{ fontWeight: 'bold', color: 'error.dark' }}>
                      Synthetic Chemicals
                    </Typography>
                    <Typography variant="body2">
                      High efficacy against exposed mites
                    </Typography>
                  </Paper>
                  
                  <Paper sx={{ p: 1.5, bgcolor: 'background.paper' }}>
                    <Typography variant="subtitle2" sx={{ fontWeight: 'bold', color: 'success.dark' }}>
                      Organic Chemicals
                    </Typography>
                    <Typography variant="body2">
                      Natural substances that kill mites
                    </Typography>
                  </Paper>
                  
                  <Paper sx={{ p: 1.5, bgcolor: 'background.paper' }}>
                    <Typography variant="subtitle2" sx={{ fontWeight: 'bold', color: 'warning.dark' }}>
                      Formic Acid
                    </Typography>
                    <Typography variant="body2">
                      Penetrates cappings but works best without brood
                    </Typography>
                  </Paper>
                </Box>
                
                <Box sx={{ mt: 2, p: 1.5, bgcolor: alpha('#f44336', 0.1), borderRadius: 1 }}>
                  <Typography variant="subtitle2" sx={{ fontWeight: 'bold', color: 'error.dark' }}>
                    Result:
                  </Typography>
                  <Typography variant="body2">
                    Kills mites that are now exposed (not hiding in capped brood)
                  </Typography>
                </Box>
              </Paper>
            </Grid>
          </Grid>
          
          {/* Bottom section: Combined effectiveness */}
          <Box 
            sx={{ 
              mt: 3, 
              p: 2, 
              bgcolor: alpha('#4caf50', 0.1), 
              borderRadius: 2,
              border: '1px dashed',
              borderColor: 'success.main'
            }}
          >
            <Typography variant="h6" sx={{ color: 'success.main', display: 'flex', alignItems: 'center' }}>
              <CheckCircleOutlineIcon sx={{ mr: 1 }} />
              Combined Strategy Benefits
            </Typography>
            
            <Grid container spacing={2} sx={{ mt: 1 }}>
              <Grid item xs={12} md={4}>
                <Box sx={{ display: 'flex', alignItems: 'center' }}>
                  <Box sx={{ width: 40, height: 40, borderRadius: '50%', bgcolor: 'success.main', color: 'white', display: 'flex', alignItems: 'center', justifyContent: 'center', mr: 2, fontWeight: 'bold' }}>
                    1
                  </Box>
                  <Typography variant="body2">
                    <strong>Higher Efficacy:</strong> Up to 95% mite reduction vs. 60-80% with single treatments
                  </Typography>
                </Box>
              </Grid>
              
              <Grid item xs={12} md={4}>
                <Box sx={{ display: 'flex', alignItems: 'center' }}>
                  <Box sx={{ width: 40, height: 40, borderRadius: '50%', bgcolor: 'success.main', color: 'white', display: 'flex', alignItems: 'center', justifyContent: 'center', mr: 2, fontWeight: 'bold' }}>
                    2
                  </Box>
                  <Typography variant="body2">
                    <strong>Reduced Resistance:</strong> Prevents mites from developing chemical resistance
                  </Typography>
                </Box>
              </Grid>
              
              <Grid item xs={12} md={4}>
                <Box sx={{ display: 'flex', alignItems: 'center' }}>
                  <Box sx={{ width: 40, height: 40, borderRadius: '50%', bgcolor: 'success.main', color: 'white', display: 'flex', alignItems: 'center', justifyContent: 'center', mr: 2, fontWeight: 'bold' }}>
                    3
                  </Box>
                  <Typography variant="body2">
                    <strong>Lower Chemical Usage:</strong> Reduces the amount of chemicals needed
                  </Typography>
                </Box>
              </Grid>
            </Grid>
          </Box>
        </Box>
      </Paper>

      <Paper elevation={3} sx={{ p: 3, mb: 4 }}>
        <Typography 
          variant="h6" 
          gutterBottom 
          sx={{ 
            display: 'flex',
            alignItems: 'center',
            gap: 1,
            color: '#F2994A',
            fontWeight: 600
          }}
        >
          Personalized Recommendations
        </Typography>
        
        <List>
          {getPersonalizedRecommendations().map((rec, index) => (
            <ListItem key={index}>
              <ListItemIcon>
                <AssignmentIcon />
              </ListItemIcon>
              <ListItemText 
                primary={rec.title}
                secondary={rec.description}
              />
            </ListItem>
          ))}
        </List>
      </Paper>

      <Paper elevation={3} sx={{ p: 3, mb: 4 }}>
        <Typography 
          variant="h6" 
          gutterBottom 
          sx={{ 
            display: 'flex',
            alignItems: 'center',
            gap: 1,
            color: '#F2994A',
            fontWeight: 600
          }}
        >
          Seasonal Advice
        </Typography>
        <Grid container spacing={3}>
          <Grid item xs={12} md={6}>
            <Card sx={{ height: '100%', bgcolor: 'background.default' }}>
              <CardContent>
                <Typography variant="h6" color="primary" gutterBottom>
                  Recommendations for {getSeasonalAdvice()}
                </Typography>
                <List>
                  {getSeasonalTips().map((tip, index) => (
                    <ListItem key={index}>
                      <ListItemIcon>
                        <AssignmentIcon color="primary" />
                      </ListItemIcon>
                      <ListItemText primary={tip} />
                    </ListItem>
                  ))}
                </List>
              </CardContent>
            </Card>
          </Grid>
          <Grid item xs={12} md={6}>
            <Card sx={{ height: '100%', bgcolor: 'background.default' }}>
              <CardContent>
                <Typography variant="h6" color="primary" gutterBottom>
                  General Information
                </Typography>
                <List>
                  <ListItem>
                    <ListItemIcon>
                      <WarningIcon color="warning" />
                    </ListItemIcon>
                    <ListItemText 
                      primary="Action Thresholds" 
                      secondary="3% - Consider treatment | 5% - Urgent treatment needed"
                    />
                  </ListItem>
                  <ListItem>
                    <ListItemIcon>
                      <CalendarTodayIcon color="primary" />
                    </ListItemIcon>
                    <ListItemText 
                      primary="Monitoring Frequency" 
                      secondary="Monthly during active season, every 15 days if high infestation"
                    />
                  </ListItem>
                  <ListItem>
                    <ListItemIcon>
                      <BugReportIcon color="error" />
                    </ListItemIcon>
                    <ListItemText 
                      primary="Warning Signs" 
                      secondary="Deformed wing bees, mortality at entrance, spotty brood pattern"
                    />
                  </ListItem>
                </List>
              </CardContent>
            </Card>
          </Grid>
        </Grid>
      </Paper>

      <Paper elevation={3} sx={{ p: 3, mb: 4 }}>
        <Typography 
          variant="h6" 
          gutterBottom 
          sx={{ 
            display: 'flex',
            alignItems: 'center',
            gap: 1,
            color: '#F2994A',
            fontWeight: 600
          }}
        >
          Additional Resources
        </Typography>
        <Grid container spacing={3}>
          <Grid item xs={12} md={4}>
            <Card sx={{ height: '100%', bgcolor: 'background.default' }}>
              <CardContent>
                <Typography variant="h6" color="primary" gutterBottom>
                  Documentation
                </Typography>
                <List dense>
                  <ListItem>
                    <ListItemIcon>
                      <AssignmentIcon />
                    </ListItemIcon>
                    <ListItemText 
                      primary="Treatment Guide" 
                      secondary="Complete application manual"
                    />
                  </ListItem>
                  <ListItem>
                    <ListItemIcon>
                      <AssignmentIcon />
                    </ListItemIcon>
                    <ListItemText 
                      primary="Monitoring Methods" 
                      secondary="Techniques and procedures"
                    />
                  </ListItem>
                </List>
              </CardContent>
            </Card>
          </Grid>
          <Grid item xs={12} md={4}>
            <Card sx={{ height: '100%', bgcolor: 'background.default' }}>
              <CardContent>
                <Typography variant="h6" color="primary" gutterBottom>
                  Useful Contacts
                </Typography>
                <List dense>
                  <ListItem>
                    <ListItemIcon>
                      <LocalHospitalIcon />
                    </ListItemIcon>
                    <ListItemText 
                      primary="Local Veterinarian" 
                      secondary="For treatment prescriptions"
                    />
                  </ListItem>
                  <ListItem>
                    <ListItemIcon>
                      <BeehiveIcon />
                    </ListItemIcon>
                    <ListItemText 
                      primary="Beekeeping Association" 
                      secondary="Support and advice"
                    />
                  </ListItem>
                </List>
              </CardContent>
            </Card>
          </Grid>
          <Grid item xs={12} md={4}>
            <Card sx={{ height: '100%', bgcolor: 'background.default' }}>
              <CardContent>
                <Typography variant="h6" color="primary" gutterBottom>
                  Next Steps
                </Typography>
                <List dense>
                  <ListItem>
                    <ListItemIcon>
                      <AccessTimeIcon />
                    </ListItemIcon>
                    <ListItemText 
                      primary="Schedule Next Monitoring" 
                      secondary={getNextMonitoringDate()}
                    />
                  </ListItem>
                  <ListItem>
                    <ListItemIcon>
                      <ThermostatIcon />
                    </ListItemIcon>
                    <ListItemText 
                      primary="Check Conditions" 
                      secondary="Adequate temperature and humidity"
                    />
                  </ListItem>
                </List>
              </CardContent>
            </Card>
          </Grid>
        </Grid>
      </Paper>

      <Box sx={{ mt: 4 }}>
        <Typography variant="body1" color="text.secondary" align="center" sx={{ mb: 2 }}>
          This report is a support tool. Always consult with a veterinary professional 
          before applying any treatment. Keep this report for your records and follow-up.
        </Typography>
        
        <Box sx={{ display: 'flex', justifyContent: 'center', gap: 2, mt: 2 }}>
          <Stack direction="row" spacing={2} justifyContent="center">
            <Button
              variant="contained"
              color="primary"
              onClick={handleSaveTest}
              disabled={isSaving}
              sx={{ minWidth: 200 }}
            >
              {isSaving ? 'Saving...' : 'Save Report'}
            </Button>
            <TreatmentReportPDF
              assessmentDate={new Date(assessmentDate)}
              beekeepingType={beekeepingType || 'Not specified'}
              timePerHive={timePerHive || 'Not specified'}
              hiveType={hiveType || 'Not specified'}
              frames={frames?.toString() || 'Not specified'}
              geneticResistance={geneticResistance || 'Not specified'}
              treatmentAvailable={treatmentAvailable || 'Not specified'}
              infestationLevel={infestationLevel || 'Not specified'}
              reference={editedReference || reference || 'Not specified'}
              recommendedTreatments={selectedTreatments.map(treatment => ({
                ...treatment,
                type: treatment.type || 'Synthetic Chemical',
                description: `${treatment.name} is a ${treatment.type || 'Synthetic Chemical'} treatment with ${treatment.effectiveness}% effectiveness.`,
                cost: treatment.cost || 'Medium',
                availability: treatment.availability || 'Available',
                restrictions: 'Follow manufacturer instructions',
                advantages: [
                  `${treatment.effectiveness}% effectiveness rate`,
                  `Application time: ${treatment.applicationTime} minutes`,
                  treatment.type === 'Organic Chemical' ? 'Environmentally friendly' : 'Fast acting'
                ],
                disadvantages: [
                  treatment.type === 'Organic Chemical' ? 'May require more frequent applications' : 'May have chemical residues',
                  'Requires proper safety equipment',
                  'Temperature dependent'
                ]
              }))}
              currentInfestation={infestationRate || 0}
              projectedInfestation={[calculateInfestationProjection(infestationRate || 0, selectedTreatments?.[0]?.effectiveness || 0)]}
              treatmentStartDate={new Date()}
              treatmentEndDate={new Date(Date.now() + 30 * 24 * 60 * 60 * 1000)}
              currentRiskLevel={getRiskLevel(infestationLevel || 'yellow')}
              afterTreatmentRiskLevel={getRiskLevel(infestationLevel || 'yellow') * (1 - (selectedTreatments?.[0]?.effectiveness || 0) / 100)}
            />
            <Button
              variant="contained"
              color="secondary"
              onClick={() => {
                dispatch(resetVarrometerState());
                navigate('/varrometer');
              }}
              sx={{ minWidth: 200 }}
            >
              Start new test
            </Button>
          </Stack>
        </Box>
      </Box>

      <Dialog open={openDialog} onClose={handleCloseDialog}>
        <DialogTitle>Login Required</DialogTitle>
        <DialogContent>
          <DialogContentText>
            You need to be logged in to save reports. Please log in to continue.
          </DialogContentText>
        </DialogContent>
        <DialogActions>
          <Button onClick={handleCloseDialog}>Close</Button>
        </DialogActions>
      </Dialog>

      <Snackbar 
        open={snackbar.open} 
        autoHideDuration={6000} 
        onClose={handleCloseSnackbar}
        anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}
      >
        <Alert 
          onClose={handleCloseSnackbar} 
          severity={snackbar.severity}
          sx={{ width: '100%' }}
        >
          {snackbar.message}
        </Alert>
      </Snackbar>
    </Box>
  );
};

export default TreatmentResults;
