import React, { useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { RootState } from '../../../store/store';
import { updateVarrometerState } from '../../../store/varrometerSlice';
import { 
  BeekeepingType, 
  TimePerHive, 
  HiveType, 
  GeneticResistance, 
  TreatmentAvailability, 
  ColonyStrength 
} from '../../../types/varrometer';
import { 
  beekeepingOptions, 
  timeOptions, 
  hiveOptions, 
  geneticResistanceOptions, 
  treatmentAvailabilityOptions 
} from '../../../constants/introductionOptions';
import {
  Stack,
  Typography,
  Button,
  Box,
  Container,
  Grid,
  Card,
  CardContent,
  CardActionArea,
  Stepper,
  Step,
  StepLabel,
  Paper,
  alpha,
  TextField,
  InputAdornment,
  Slider,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  CardMedia,
  Checkbox,
  styled,
  Chip,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Link,
  Fade,
  Slide,
  Theme
} from '@mui/material';
import AccessTimeIcon from '@mui/icons-material/AccessTime';
import NatureIcon from '@mui/icons-material/Nature';
import HomeIcon from '@mui/icons-material/Home';
import AssignmentIcon from '@mui/icons-material/Assignment';
import LabelIcon from '@mui/icons-material/Label';
import CalendarTodayIcon from '@mui/icons-material/CalendarToday';
import ViewModuleIcon from '@mui/icons-material/ViewModule';
import ViewInArIcon from '@mui/icons-material/ViewInAr';
import MedicationIcon from '@mui/icons-material/Medication';
import InfoIcon from '@mui/icons-material/Info';
import BiotechIcon from '@mui/icons-material/Biotech';
import LocalPharmacyIcon from '@mui/icons-material/LocalPharmacy';

// Constantes para el calendario
const MONTHS = [
  'January', 'February', 'March', 'April', 'May', 'June',
  'July', 'August', 'September', 'October', 'November', 'December'
];

const SEASONS = {
  WINTER: { name: 'Winter', color: '#90caf9', treatment: 'Oxalic acid treatment' },
  SPRING: { name: 'Spring', color: '#a5d6a7', treatment: 'Formic acid / Thymol' },
  SUMMER: { name: 'Summer', color: '#ffcc80', treatment: 'Biotechnical methods' },
  AUTUMN: { name: 'Autumn', color: '#ffab91', treatment: 'Main varroa treatment' }
};

const getMonthSeason = (month: number) => {
  if (month <= 1 || month === 11) return SEASONS.WINTER;
  if (month >= 2 && month <= 4) return SEASONS.SPRING;
  if (month >= 5 && month <= 7) return SEASONS.SUMMER;
  return SEASONS.AUTUMN;
};

// Hero section styles
const HeroSection = styled(Box)(({ theme }: { theme: Theme }) => ({
  position: 'relative',
  color: 'white',
  width: '100%',
  minHeight: '20vh',
  display: 'flex',
  alignItems: 'center',
  justifyContent: 'center',
  textAlign: 'center',
  overflow: 'hidden',
  marginTop: '0',
  marginBottom: theme.spacing(4),
  padding: theme.spacing(4, 0),
  '&::before': {
    content: '""',
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    background: `linear-gradient(45deg, ${theme.palette.primary.main}dd 30%, ${theme.palette.secondary.main}dd 90%)`,
    zIndex: 1
  }
}));

const HeroContent = styled(Box)({
  position: 'relative',
  zIndex: 2,
  width: '100%',
  padding: '20px'
});

const BOTTOM_BOARD_TYPES = ['With tubes', 'With a wire mesh', 'Without tubes/wire mesh'];
const VETERINARY_PRODUCTS = [
  'Aucun', 'Amicel Varroa', 'AMO Varroxal 85 %', 'ApiFor60®', 
  'Apibioxal®', 'ApiLifeVar', 'Apiguard®', 'Apistan®', 'Apitraz®', 'Apivar®', 'ApiWarol®',
  'Bayvarol®', 'Biowar®', 'Checkmite+®', 'Dany\'s BienenWohl', 'Ecostop-lamellae',
  'Ecoxal®', 'Formidol®', 'Gabon® PF', 'MAQS®', 'Oxuvar®', 'Oxybee', 'Perizin®',
  'PolyVar Yellow 275 mg', 'Thymovar®', 'Varachet forte', 'Varatraz®', 'Varidol®',
  'Varostop®', 'VarroMed', 'Varterminator'
];

interface State {
  frames: number;
  actionTime: string;
  bottomBoard: string;
  veterinaryProducts: string[];
  geneticResistance: GeneticResistance | undefined;
  treatmentAvailability: TreatmentAvailability | undefined;
  colonyStrength: ColonyStrength | undefined;
}

const bottomBoardOptions = [
  {
    value: 'solid',
    label: 'Solid Bottom Board',
    description: 'Traditional solid bottom board',
    image: '/images/11.jpg'
  },
  {
    value: 'screened',
    label: 'Screened Bottom Board',
    description: 'Ventilated bottom board with screen',
    image: '/images/12.jpg'
  },
  {
    value: 'hybrid',
    label: 'Hybrid Bottom Board',
    description: 'Convertible bottom board (solid/screened)',
    image: '/images/14.jpg'
  }
];

const veterinaryProductOptions = [
  { value: 'none', label: 'Aucun', description: 'No treatment used' },
  { value: 'amicel', label: 'Amicel Varroa', description: 'Amitraz-based treatment' },
  { value: 'amo-varroxal', label: 'AMO Varroxal 85 %', description: 'Oxalic acid treatment' },
  { value: 'apibioxal', label: 'Apibioxal®', description: 'Oxalic acid treatment' },
  { value: 'apifor60', label: 'ApiFor60®', description: 'Formic acid treatment' },
  { value: 'apiguard', label: 'Apiguard®', description: 'Thymol-based treatment' },
  { value: 'apilife-var', label: 'ApiLifeVar', description: 'Essential oil treatment' },
  { value: 'apistan', label: 'Apistan®', description: 'Tau-fluvalinate treatment' },
  { value: 'apitraz', label: 'Apitraz®', description: 'Amitraz-based treatment' },
  { value: 'apivar', label: 'Apivar®', description: 'Amitraz-based treatment' },
  { value: 'apiwarol', label: 'ApiWarol®', description: 'Amitraz-based treatment' },
  { value: 'bayvarol', label: 'Bayvarol®', description: 'Flumethrin treatment' },
  { value: 'biowar', label: 'Biowar®', description: 'Organic treatment' },
  { value: 'checkmite', label: 'Checkmite+®', description: 'Coumaphos treatment' },
  { value: 'danys', label: 'Dany\'s BienenWohl', description: 'Oxalic acid treatment' },
  { value: 'ecostop', label: 'Ecostop-lamellae', description: 'Natural treatment' },
  { value: 'ecoxal', label: 'Ecoxal®', description: 'Oxalic acid treatment' },
  { value: 'formidol', label: 'Formidol®', description: 'Formic acid treatment' },
  { value: 'gabon', label: 'Gabon® PF', description: 'Synthetic treatment' },
  { value: 'maqs', label: 'MAQS®', description: 'Formic acid treatment' },
  { value: 'oxuvar', label: 'Oxuvar®', description: 'Oxalic acid treatment' },
  { value: 'oxybee', label: 'Oxybee', description: 'Oxalic acid treatment' },
  { value: 'perizin', label: 'Perizin®', description: 'Coumaphos treatment' },
  { value: 'polyvar', label: 'PolyVar Yellow 275 mg', description: 'Flumethrin treatment' },
  { value: 'thymovar', label: 'Thymovar®', description: 'Thymol-based treatment' },
  { value: 'varachet', label: 'Varachet forte', description: 'Synthetic treatment' },
  { value: 'varatraz', label: 'Varatraz®', description: 'Amitraz-based treatment' },
  { value: 'varidol', label: 'Varidol®', description: 'Synthetic treatment' },
  { value: 'varostop', label: 'Varostop®', description: 'Synthetic treatment' },
  { value: 'varterminator', label: 'Varterminator', description: 'Synthetic treatment' },
  { value: 'varromed', label: 'VarroMed', description: 'Organic acid treatment' },
  { value: 'varroMed', label: 'VarroMed', description: 'Organic acid treatment' }
];

const frameOptions = Array.from({ length: 15 }, (_, i) => ({
  value: i + 1,
  label: `${i + 1} Frames`,
  description: `${i + 1} frames of production colony fully covered with bees`
}));

const actionTimeOptions = MONTHS.map(month => ({
  value: month,
  label: month,
  description: `Perform the action during ${month}`
}));

const StyledCard = styled(Card)(({ theme }: { theme: Theme }) => ({
  backgroundColor: theme.palette.background.paper,
  borderRadius: theme.shape.borderRadius,
  transition: 'transform 0.2s, box-shadow 0.2s',
  '&:hover': {
    transform: 'translateY(-4px)',
    boxShadow: (theme: Theme) => theme.shadows[4]
  },
  height: '100%',
  display: 'flex',
  flexDirection: 'column'
}));

const Introduction: React.FC = () => {
  const dispatch = useDispatch();
  const varrometerState = useSelector((state: RootState) => state.varrometer);
  const { 
    beekeepingType, 
    timePerHive, 
    hiveType, 
    reference, 
    assessmentDate, 
    geneticResistance, 
    treatmentAvailable 
  } = varrometerState;
  const [activeStep, setActiveStep] = React.useState(0);
  const [selectedLetter, setSelectedLetter] = useState<string>('All');
  const [state, setState] = useState<State>({
    frames: 8,
    actionTime: '',
    bottomBoard: '',
    geneticResistance: 'none', 
    treatmentAvailability: 'veterinary', 
    veterinaryProducts: [],
    colonyStrength: 'medium' 
  });
  const [selectedProduct, setSelectedProduct] = useState<string | null>(null);
  const [dialogOpen, setDialogOpen] = useState(false);
  const [slideDirection, setSlideDirection] = useState<'left' | 'right'>('left');

  // Get today's date in YYYY-MM-DD format for the default assessment date
  const today = new Date().toISOString();

  // Initialize assessment date with today's date when component mounts if not already set
  useEffect(() => {
    if (!assessmentDate) {
      dispatch(updateVarrometerState({ assessmentDate: today }));
    }
  }, [dispatch, assessmentDate]);

  // Función auxiliar para determinar el período del año
  const getDefaultActionTime = () => {
    const month = new Date().getMonth();
    if (month >= 0 && month <= 1) return 'Jan/Feb';
    if (month >= 2 && month <= 3) return 'Mar/Apr';
    if (month >= 4 && month <= 5) return 'May/Jun';
    if (month >= 6 && month <= 7) return 'Jul/Aug';
    if (month >= 8 && month <= 9) return 'Sep/Oct';
    return 'Nov/Dec';
  };

  // Establecer el actionTime por defecto cuando se monta el componente
  useEffect(() => {
    setState(prev => ({
      ...prev,
      actionTime: getDefaultActionTime()
    }));
  }, []);

  const handleReferenceChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    dispatch(updateVarrometerState({ reference: event.target.value }));
  };

  const treatmentInfo: Record<string, { description: string, type: string, usage: string, source: string }> = {
    'Aucun': {
      description: 'No treatment used during the previous year.',
      type: 'No treatment',
      usage: 'Not applicable - No treatment was applied',
      source: 'https://www.ema.europa.eu/en/veterinary-medicines'
    },
    'Amicel Varroa': {
      description: 'An amitraz-based treatment for controlling Varroa mites in honey bee colonies.',
      type: 'Amitraz-based treatment',
      usage: 'Follow manufacturer instructions for proper application. Generally requires strips placed in the brood chamber.',
      source: 'https://www.ema.europa.eu/en/documents/product-information/amicel-varroa-epar-product-information_en.pdf'
    },
    'AMO Varroxal 85 %': {
      description: 'An oxalic acid-based treatment effective against Varroa mites.',
      type: 'Organic acid treatment',
      usage: 'Apply as directed when colonies are broodless. Typically used in winter.',
      source: 'https://www.ema.europa.eu/en/documents/product-information/amo-varroxal-epar-product-information_en.pdf'
    },
    'ApiFor60®': {
      description: 'A formic acid-based treatment for Varroa control in honey bee colonies.',
      type: 'Organic acid treatment',
      usage: 'Apply when temperature is between 10-29.5°C. Follow dosage instructions carefully.',
      source: 'https://www.ema.europa.eu/en/documents/product-information/apifor60-epar-product-information_en.pdf'
    },
    'Apibioxal®': {
      description: 'An oxalic acid-based treatment specifically formulated for Varroa control.',
      type: 'Organic acid treatment',
      usage: 'Best used during broodless periods. Can be applied by sublimation or trickling.',
      source: 'https://www.ema.europa.eu/en/documents/product-information/apibioxal-epar-product-information_en.pdf'
    },
    'ApiLifeVar': {
      description: 'A natural treatment containing thymol, eucalyptol, menthol and camphor essential oils.',
      type: 'Essential oil based treatment',
      usage: 'Apply when temperatures are between 15-25°C. Three applications at 7-10 day intervals are required.',
      source: 'https://www.ema.europa.eu/en/documents/product-information/apilifevar-epar-product-information_en.pdf'
    },
    'Apiguard®': {
      description: 'A thymol-based treatment that uses natural thyme oil to control Varroa mites.',
      type: 'Essential oil based treatment',
      usage: 'Apply when temperatures are between 15-40°C. Two treatments of 2 weeks each are required.',
      source: 'https://www.ema.europa.eu/en/documents/product-information/apiguard-epar-product-information_en.pdf'
    },
    'Apistan®': {
      description: 'A tau-fluvalinate based treatment for controlling Varroa mites in honey bee colonies.',
      type: 'Synthetic pyrethroid',
      usage: 'Two strips per brood box for 6-8 weeks. Do not use during honey flow.',
      source: 'https://www.ema.europa.eu/en/documents/product-information/apistan-epar-product-information_en.pdf'
    },
    'Apitraz®': {
      description: 'An amitraz-based treatment delivered via polymer strips for consistent release.',
      type: 'Amitraz-based treatment',
      usage: 'Place strips in brood chamber for 6 weeks. Remove after treatment.',
      source: 'https://www.ema.europa.eu/en/documents/product-information/apitraz-epar-product-information_en.pdf'
    },
    'Apivar®': {
      description: 'The original amitraz-based treatment against varroa mites. Comes in the form of plastic strips.',
      type: 'Amitraz-based treatment',
      usage: 'Place 1 strip for 5 frames of bees (usually 2 strips per brood chamber). Can be used at any time of year when there is activity in the hive.',
      source: 'https://www.ema.europa.eu/en/documents/product-information/apivar-epar-product-information_en.pdf'
    },
    'ApiWarol®': {
      description: 'An amitraz-based treatment against varroa mites that comes in the form of plastic strips to insert into the hive.',
      type: 'Amitraz-based treatment',
      usage: 'Place 1 strip for 5 frames of bees (usually 2 strips per brood chamber). Can be used at any time of year when there is activity in the hive.',
      source: 'https://www.ema.europa.eu/en/documents/product-information/apiwarol-epar-product-information_en.pdf'
    },
    'Bayvarol®': {
      description: 'A flumethrin-based treatment effective against Varroa mites.',
      type: 'Synthetic pyrethroid',
      usage: '4 strips per brood chamber for 6 weeks. Remove strips after treatment.',
      source: 'https://www.ema.europa.eu/en/documents/product-information/bayvarol-epar-product-information_en.pdf'
    },
    'Biowar®': {
      description: 'An organic treatment based on natural compounds for Varroa control.',
      type: 'Organic treatment',
      usage: 'Follow manufacturer instructions for proper application timing and dosage.',
      source: 'https://www.ema.europa.eu/en/documents/product-information/biowar-epar-product-information_en.pdf'
    },
    'Checkmite+®': {
      description: 'A coumaphos-based treatment for controlling both Varroa mites and small hive beetles.',
      type: 'Organophosphate treatment',
      usage: 'Two strips per brood chamber for 42-45 days. Remove after treatment.',
      source: 'https://www.ema.europa.eu/en/documents/product-information/checkmite-plus-epar-product-information_en.pdf'
    },
    'Dany\'s BienenWohl': {
      description: 'An oxalic acid-based treatment developed specifically for Varroa control.',
      type: 'Organic acid treatment',
      usage: 'Best used during broodless periods. Follow manufacturer instructions carefully.',
      source: 'https://www.ema.europa.eu/en/documents/product-information/danys-bienenwohl-epar-product-information_en.pdf'
    },
    'Ecostop-lamellae': {
      description: 'A natural treatment using essential oils and organic compounds.',
      type: 'Natural treatment',
      usage: 'Apply according to manufacturer instructions. Monitor temperature requirements.',
      source: 'https://www.ema.europa.eu/en/documents/product-information/ecostop-lamellae-epar-product-information_en.pdf'
    },
    'Ecoxal®': {
      description: 'An oxalic acid-based treatment for Varroa control.',
      type: 'Organic acid treatment',
      usage: 'Apply during broodless periods for best results. Follow safety instructions.',
      source: 'https://www.ema.europa.eu/en/documents/product-information/ecoxal-epar-product-information_en.pdf'
    },
    'Formidol®': {
      description: 'A formic acid-based treatment effective against Varroa mites.',
      type: 'Organic acid treatment',
      usage: 'Use when temperature is between 10-29.5°C. Follow dosage carefully.',
      source: 'https://www.ema.europa.eu/en/documents/product-information/formidol-epar-product-information_en.pdf'
    },
    'Gabon® PF': {
      description: 'A synthetic treatment designed for effective Varroa control.',
      type: 'Synthetic treatment',
      usage: 'Follow manufacturer instructions for proper application timing.',
      source: 'https://www.ema.europa.eu/en/documents/product-information/gabon-pf-epar-product-information_en.pdf'
    },
    'MAQS®': {
      description: 'Mite Away Quick Strips - A formic acid-based treatment that can be used with honey supers on.',
      type: 'Organic acid treatment',
      usage: 'Two strips for 7 days. Can be used during honey flow. Temperature should be between 10-29.5°C.',
      source: 'https://www.ema.europa.eu/en/documents/product-information/maqs-epar-product-information_en.pdf'
    },
    'Oxuvar®': {
      description: 'An oxalic acid-based treatment for use in honey bee colonies.',
      type: 'Organic acid treatment',
      usage: 'Best used in broodless periods. Can be applied by trickling or spraying.',
      source: 'https://www.ema.europa.eu/en/documents/product-information/oxuvar-epar-product-information_en.pdf'
    },
    'Oxybee': {
      description: 'An oxalic acid dihydrate-based treatment with additional compounds for enhanced efficacy.',
      type: 'Organic acid treatment',
      usage: 'Apply during broodless period. Follow temperature requirements.',
      source: 'https://www.ema.europa.eu/en/documents/product-information/oxybee-epar-product-information_en.pdf'
    },
    'Perizin®': {
      description: 'A coumaphos-based treatment for controlling Varroa mites.',
      type: 'Organophosphate treatment',
      usage: 'Apply according to manufacturer instructions. Monitor for resistance.',
      source: 'https://www.ema.europa.eu/en/documents/product-information/perizin-epar-product-information_en.pdf'
    },
    'PolyVar Yellow 275 mg': {
      description: 'A flumethrin-based treatment in a unique delivery system.',
      type: 'Synthetic pyrethroid',
      usage: 'Place at hive entrance for extended period. Follow instructions carefully.',
      source: 'https://www.ema.europa.eu/en/documents/product-information/polyvar-yellow-epar-product-information_en.pdf'
    },
    'Thymovar®': {
      description: 'A thymol-based treatment for controlling varroa mites in honey bee colonies.',
      type: 'Essential oil based treatment',
      usage: 'Two consecutive 3-4 week treatments are required. Use when temperature is between 15-30°C.',
      source: 'https://www.ema.europa.eu/en/documents/product-information/thymovar-epar-product-information_en.pdf'
    },
    'Varachet forte': {
      description: 'A synthetic treatment formulated for Varroa control.',
      type: 'Synthetic treatment',
      usage: 'Follow manufacturer instructions for proper application timing.',
      source: 'https://www.ema.europa.eu/en/documents/product-information/varachet-forte-epar-product-information_en.pdf'
    },
    'Varatraz®': {
      description: 'An amitraz-based treatment for Varroa mite control.',
      type: 'Amitraz-based treatment',
      usage: 'Apply strips in brood chamber. Remove after treatment period.',
      source: 'https://www.ema.europa.eu/en/documents/product-information/varatraz-epar-product-information_en.pdf'
    },
    'Varidol®': {
      description: 'A synthetic acaricide for controlling Varroa mites.',
      type: 'Synthetic treatment',
      usage: 'Follow manufacturer guidelines for proper application method.',
      source: 'https://www.ema.europa.eu/en/documents/product-information/varidol-epar-product-information_en.pdf'
    },
    'Varostop®': {
      description: 'A synthetic treatment designed for Varroa control in bee colonies.',
      type: 'Synthetic treatment',
      usage: 'Apply according to manufacturer instructions. Monitor effectiveness.',
      source: 'https://www.ema.europa.eu/en/documents/product-information/varostop-epar-product-information_en.pdf'
    },
    'Varterminator': {
      description: 'A synthetic acaricide treatment specifically designed for Varroa mite control in honey bee colonies.',
      type: 'Synthetic treatment',
      usage: 'Apply according to manufacturer instructions. Monitor colony during treatment period.',
      source: 'https://www.ema.europa.eu/en/documents/product-information/varterminator-epar-product-information_en.pdf'
    },
    'VarroMed': {
      description: 'A combination of formic acid and oxalic acid dihydrate for varroa control.',
      type: 'Organic acid treatment',
      usage: 'Multiple treatments depending on season and infestation level. Can be used during honey flow.',
      source: 'https://www.ema.europa.eu/en/documents/product-information/varromed-epar-product-information_en.pdf'
    }
  };
  

  const steps = [
    { id: 'reference', label: 'Reference', icon: <AssignmentIcon /> },
    { id: 'beekeeping', label: 'Beekeeping Type', icon: <NatureIcon /> },
    { id: 'time', label: 'Time per Hive', icon: <AccessTimeIcon /> },
    { id: 'genetic', label: 'Genetic Resistance', icon: <BiotechIcon /> },
    { id: 'treatment', label: 'Treatment Accessibility', icon: <LocalPharmacyIcon /> },
    { id: 'previous', label: 'Previous Treatments', icon: <MedicationIcon /> }
  ];

  // Función para manejar cambios en los inputs
  const handleCardClick = (value: any, field: string) => {
    handleInputChange(field, value);
    // Avanzar automáticamente al siguiente paso después de seleccionar una opción
    if (activeStep < steps.length - 1) {
      setActiveStep(activeStep + 1);
    }
  };

  const handleInputChange = (field: string, value: any) => {
    setState(prev => ({ ...prev, [field]: value }));
    
    // Actualizar el estado global de Redux
    const updatedState: any = {};

    // Solo actualizar el campo específico en Redux
    if (field === 'geneticResistance') {
      updatedState.geneticResistance = value;
    } else if (field === 'treatmentAvailability') {
      updatedState.treatmentAvailability = value;
    } else if (field === 'frames') {
      updatedState.colonyStrength = calculateColonyStrength(value);
    }

    if (Object.keys(updatedState).length > 0) {
      dispatch(updateVarrometerState(updatedState));
    }
  };

  const handleBeekeepingTypeSelect = (value: BeekeepingType) => {
    dispatch(updateVarrometerState({ beekeepingType: value }));
    setActiveStep((prev) => prev + 1);
  };

  const handleTimeSelect = (value: TimePerHive) => {
    dispatch(updateVarrometerState({ timePerHive: value }));
    setActiveStep((prev) => prev + 1);
  };

  const handleHiveTypeSelect = (value: HiveType) => {
    dispatch(updateVarrometerState({ hiveType: value }));
    setActiveStep((prev) => prev + 1);
  };

  const handleDateChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const selectedDate = event.target.value;
    dispatch(updateVarrometerState({ assessmentDate: selectedDate }));
  };

  const calculateColonyStrength = (frames: number): ColonyStrength => {
    if (frames > 6) return 'strong';
    if (frames === 6) return 'medium';
    if (frames < 5) return 'weak';
    return 'nuclei';
  };

  const handleVeterinaryProductToggle = (value: string) => {
    const currentProducts = state.veterinaryProducts;
    const newProducts = currentProducts.includes(value)
      ? currentProducts.filter(product => product !== value)
      : [...currentProducts, value];
    setState({ ...state, veterinaryProducts: newProducts });
  };

  const handleReadMore = (product: string, event: React.MouseEvent) => {
    event.stopPropagation();
    setSelectedProduct(product);
    setDialogOpen(true);
  };

  const canContinue = () => {
    switch (activeStep) {
      case 0: return !!reference && !!assessmentDate;
      case 1: return !!beekeepingType;
      case 2: return !!timePerHive;
      case 3: return !!state.geneticResistance;
      case 4: return !!state.treatmentAvailability;
      case 5: return true; // Permitir continuar sin seleccionar tratamientos
      default: return false;
    }
  };

  const handleBack = () => {
    setSlideDirection('right');
    setActiveStep((prevActiveStep) => prevActiveStep - 1);
  };

  const handleNext = () => {
    setSlideDirection('left');
    
    if (activeStep === steps.length - 1) {
      dispatch(updateVarrometerState({
        frames: state.frames,
        actionTime: state.actionTime,
        bottomBoard: state.bottomBoard,
        veterinaryProducts: state.veterinaryProducts,
        currentPhase: 'medications'
      }));
    }
    setActiveStep((prevStep) => prevStep + 1);
  };

  const handleFinish = () => {
    dispatch(updateVarrometerState({
      frames: state.frames,
      actionTime: state.actionTime,
      bottomBoard: state.bottomBoard,
      veterinaryProducts: state.veterinaryProducts,
      currentPhase: 'medications'
    }));
  };

  // Mantener actualizada la fuerza de la colonia
  React.useEffect(() => {
    const colonyStrength = calculateColonyStrength(state.frames);
    dispatch(updateVarrometerState({ 
      frames: state.frames,
      colonyStrength 
    }));
  }, [state.frames, dispatch]);

  const renderStep = () => {
    switch (activeStep) {
      case 0:
        return (
          <Box sx={{ p: 3 }}>
            <Typography variant="h5" gutterBottom sx={{ textAlign: 'center', mb: 3, color: 'primary.main' }}>
              Assessment Date and Reference
            </Typography>
            
            <Grid container spacing={3}>
              <Grid item xs={12} md={4}>
                <Paper elevation={2} sx={{ p: 3 }}>
                  <Typography variant="h6" gutterBottom>
                    Assessment Reference
                  </Typography>
                  <TextField
                    fullWidth
                    value={reference || ''}
                    onChange={handleReferenceChange}
                    placeholder="e.g., Spring Check 2025"
                    variant="outlined"
                    InputProps={{
                      startAdornment: (
                        <InputAdornment position="start">
                          <AssignmentIcon color="primary" />
                        </InputAdornment>
                      ),
                    }}
                  />
                  <Typography variant="body2" color="text.secondary" sx={{ mt: 1, mb: 3 }}>
                    A unique identifier for this assessment
                  </Typography>

                  <Typography variant="h6" gutterBottom>
                    Assessment Date
                  </Typography>
                  <TextField
                    fullWidth
                    type="date"
                    value={assessmentDate ? assessmentDate.split('T')[0] : ''}
                    onChange={(e) => dispatch(updateVarrometerState({ assessmentDate: e.target.value }))}
                    variant="outlined"
                    InputProps={{
                      startAdornment: (
                        <InputAdornment position="start">
                          <CalendarTodayIcon color="primary" />
                        </InputAdornment>
                      ),
                    }}
                  />
                  <Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>
                    Select the date of your assessment
                  </Typography>
                </Paper>
              </Grid>

              <Grid item xs={12} md={8}>
                <Paper elevation={2} sx={{ p: 3 }}>
                  <Box sx={{ mb: 2, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                    <Typography variant="h6">
                      Annual Treatment Calendar
                    </Typography>
                  </Box>

                  <Box sx={{ mt: 3 }}>
                    <Grid container spacing={1}>
                      {MONTHS.map((month, index) => {
                        const season = getMonthSeason(index);
                        return (
                          <Grid item xs={12} sm={6} md={3} key={month}>
                            <Paper
                              elevation={currentMonth === index ? 3 : 1}
                              sx={{
                                p: 2,
                                textAlign: 'center',
                                bgcolor: season.color,
                                border: currentMonth === index ? 2 : 0,
                                borderColor: 'primary.main',
                                position: 'relative',
                                minHeight: '100px',
                                display: 'flex',
                                flexDirection: 'column',
                                justifyContent: 'space-between',
                                '&:hover': {
                                  '& .season-info': {
                                    opacity: 1,
                                    visibility: 'visible'
                                  }
                                }
                              }}
                              onClick={() => {
                                const date = new Date();
                                date.setMonth(index);
                                dispatch(updateVarrometerState({ 
                                  assessmentDate: date.toISOString().split('T')[0] 
                                }));
                              }}
                            >
                              <Box>
                                <Typography variant="h6" sx={{ fontWeight: currentMonth === index ? 'bold' : 'normal' }}>
                                  {month}
                                </Typography>
                                <Typography variant="caption" sx={{ display: 'block', mt: 1 }}>
                                  {season.name}
                                </Typography>
                              </Box>
                              
                              <Box 
                                className="season-info"
                                sx={{ 
                                  opacity: 0,
                                  visibility: 'hidden',
                                  transition: 'all 0.3s',
                                  position: 'absolute',
                                  bottom: '100%',
                                  left: '50%',
                                  transform: 'translateX(-50%)',
                                  bgcolor: 'background.paper',
                                  p: 1.5,
                                  borderRadius: 1,
                                  boxShadow: 3,
                                  zIndex: 1,
                                  width: '200px',
                                  textAlign: 'left',
                                  '&::after': {
                                    content: '""',
                                    position: 'absolute',
                                    top: '100%',
                                    left: '50%',
                                    transform: 'translateX(-50%)',
                                    border: '8px solid transparent',
                                    borderTopColor: 'background.paper'
                                  }
                                }}
                              >
                                <Typography variant="subtitle2" sx={{ color: 'primary.main', mb: 0.5 }}>
                                  {season.name} Treatment
                                </Typography>
                                <Typography variant="body2">
                                  {season.treatment}
                                </Typography>
                              </Box>
                            </Paper>
                          </Grid>
                        );
                      })}
                    </Grid>
                  </Box>

                  <Box sx={{ mt: 3, display: 'flex', gap: 2, flexWrap: 'wrap', justifyContent: 'center' }}>
                    {Object.values(SEASONS).map((season) => (
                      <Box key={season.name} sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                        <Box 
                          sx={{ 
                            width: 16, 
                            height: 16, 
                            borderRadius: '50%',
                            bgcolor: season.color
                          }} 
                        />
                        <Typography variant="body2">{season.name}</Typography>
                      </Box>
                    ))}
                  </Box>
                </Paper>
              </Grid>
            </Grid>
          </Box>
        );
      case 1:
        return (
          <Box sx={{ p: 3 }}>
            <Typography variant="h6" gutterBottom sx={{ textAlign: 'center', mb: 3 }}>
              How much time can you dedicate to each hive?
            </Typography>
            <Box 
              sx={{ 
                display: 'flex',
                justifyContent: 'center',
                gap: 2,
                mt: 2,
                flexWrap: 'wrap'
              }}
            >
              {timeOptions.map((option, index) => (
                <Fade 
                  in={true} 
                  style={{ transitionDelay: `${index * 100}ms` }}
                  key={option.value}
                >
                  <Box sx={{ width: { xs: '100%', sm: '45%' }, maxWidth: 350 }}>
                    <StyledCard
                      sx={{
                        cursor: 'pointer',
                        transition: 'transform 0.2s, box-shadow 0.2s',
                        '&:hover': {
                          transform: 'translateY(-4px)',
                          boxShadow: (theme: Theme) => theme.shadows[4]
                        },
                        border: timePerHive === option.value ? '2px solid' : 'none',
                        borderColor: 'primary.main',
                        bgcolor: 'background.paper',
                        height: '100%'
                      }}
                      onClick={() => handleTimeSelect(option.value as TimePerHive)}
                    >
                      <CardMedia
                        component="img"
                        height="200"
                        image={option.image}
                        alt={option.label}
                        sx={{ objectFit: 'cover' }}
                      />
                      <CardContent sx={{ textAlign: 'center' }}>
                        <Typography variant="h6" gutterBottom>
                          {option.label}
                        </Typography>
                        <Typography variant="body2" color="text.secondary">
                          {option.description}
                        </Typography>
                      </CardContent>
                    </StyledCard>
                  </Box>
                </Fade>
              ))}
            </Box>
          </Box>
        );
      case 2:
        return (
          <Box sx={{ p: 3 }}>
            <Typography variant="h6" gutterBottom sx={{ textAlign: 'center', mb: 3 }}>
              What type of beekeeping do you practice?
            </Typography>
            <Grid container spacing={3} sx={{ mt: 2 }}>
              {beekeepingOptions.map((option, index) => (
                <Fade 
                  in={true} 
                  style={{ transitionDelay: `${index * 100}ms` }}
                  key={option.value}
                >
                  <Grid item xs={12} sm={6} md={4}>
                    <StyledCard
                      sx={{
                        cursor: 'pointer',
                        transition: 'transform 0.2s, box-shadow 0.2s',
                        '&:hover': {
                          transform: 'translateY(-4px)',
                          boxShadow: (theme: Theme) => theme.shadows[4]
                        },
                        border: beekeepingType === option.value ? '2px solid' : 'none',
                        borderColor: 'primary.main',
                        bgcolor: 'background.paper'
                      }}
                      onClick={() => handleBeekeepingTypeSelect(option.value as BeekeepingType)}
                    >
                      <CardMedia
                        component="img"
                        height="200"
                        sx={{
                          objectFit: 'cover',
                          width: '100%',
                          borderRadius: '8px 8px 0 0'
                        }}
                        image={option.image}
                        alt={option.label}
                      />
                      <CardContent>
                        <Typography gutterBottom variant="h6" component="div">
                          {option.label}
                        </Typography>
                        <Typography variant="body2" color="text.secondary">
                          {option.description}
                        </Typography>
                      </CardContent>
                    </StyledCard>
                  </Grid>
                </Fade>
              ))}
            </Grid>
          </Box>
        );
      case 3:
        return (
          <Box sx={{ p: 3 }}>
            <Typography variant="h6" gutterBottom sx={{ textAlign: 'center', mb: 3 }}>
             Does your colony have genetic resistance to Varroa?
            </Typography>
            <Typography variant="body2" color="text.secondary" sx={{ textAlign: 'center', mb: 2 }}>
             Select whether your colony has genetic traits for Varroa resistance.
            </Typography>
            <Grid 
              container 
              spacing={2}
              justifyContent="center"
              sx={{ mt: 2 }}
            >
              {[
                {
                  value: 'varroa_tolerant',
                  label: 'Varroa Tolerant',
                  description: 'Colony shows genetic resistance to varroa mites',
                  image: '/images/26.jpg'
                },
                {
                  value: 'normal',
                  label: 'Normal',
                  description: 'Colony has no specific genetic resistance to varroa',
                  image: '/images/27.jpg'
                }
              ].map((option) => (
                <Fade 
                  in={true} 
                  style={{ transitionDelay: '100ms' }}
                  key={option.value}
                >
                  <Grid item xs={12} sm={5} key={option.value}>
                    <StyledCard
                      sx={{
                        cursor: 'pointer',
                        transition: 'transform 0.2s, box-shadow 0.2s',
                        '&:hover': {
                          transform: 'translateY(-4px)',
                          boxShadow: (theme: Theme) => theme.shadows[4]
                        },
                        border: state.geneticResistance === option.value ? '2px solid' : 'none',
                        borderColor: 'primary.main',
                        bgcolor: 'background.paper',
                        height: '100%'
                      }}
                      onClick={() => handleCardClick(option.value, 'geneticResistance')}
                    >
                      <CardMedia
                        component="img"
                        height="200"
                        image={option.image}
                        alt={option.label}
                        sx={{ objectFit: 'cover' }}
                      />
                      <CardContent sx={{ textAlign: 'center' }}>
                        <Typography variant="h6" gutterBottom>
                          {option.label}
                        </Typography>
                        <Typography variant="body2" color="text.secondary">
                          {option.description}
                        </Typography>
                      </CardContent>
                    </StyledCard>
                  </Grid>
                </Fade>
              ))}
            </Grid>
          </Box>
        );
      case 4:
        return (
          <Box sx={{ p: 3 }}>
            <Typography variant="h6" gutterBottom sx={{ textAlign: 'center', mb: 3 }}>
             What types of treatments do you have available?
            </Typography>
            <Typography variant="body2" color="text.secondary" sx={{ textAlign: 'center', mb: 2 }}>
             Select which types of treatments are available to you.
            </Typography>
            <Grid 
              container 
              spacing={2}
              justifyContent="center"
              sx={{ mt: 2 }}
            >
              {[
                {
                  value: 'veterinary',
                  label: 'Veterinary Only',
                  description: 'Only veterinary treatments are available',
                  image: '/images/12.jpg'
                },
                {
                  value: 'pharmacy',
                  label: 'Pharmacy Available',
                  description: 'Both veterinary and pharmacy treatments are available',
                  image: '/images/14.jpg'
                },
                {
                  value: 'all_available',
                  label: 'All Available',
                  description: 'All types of treatments are available',
                  image: '/images/15.jpg'
                }
              ].map((option) => (
                <Fade 
                  in={true} 
                  style={{ transitionDelay: '100ms' }}
                  key={option.value}
                >
                  <Grid item xs={12} sm={6} md={4} key={option.value}>
                    <StyledCard
                      sx={{
                        cursor: 'pointer',
                        transition: 'transform 0.2s, box-shadow 0.2s',
                        '&:hover': {
                          transform: 'translateY(-4px)',
                          boxShadow: (theme: Theme) => theme.shadows[4]
                        },
                        border: state.treatmentAvailability === option.value ? '2px solid' : 'none',
                        borderColor: 'primary.main',
                        bgcolor: 'background.paper',
                        height: '100%'
                      }}
                      onClick={() => handleCardClick(option.value, 'treatmentAvailability')}
                    >
                      <CardMedia
                        component="img"
                        height="200"
                        image={option.image}
                        alt={option.label}
                        sx={{ objectFit: 'cover' }}
                      />
                      <CardContent sx={{ textAlign: 'center' }}>
                        <Typography variant="h6" gutterBottom>
                          {option.label}
                        </Typography>
                        <Typography variant="body2" color="text.secondary">
                          {option.description}
                        </Typography>
                      </CardContent>
                    </StyledCard>
                  </Grid>
                </Fade>
              ))}
            </Grid>
          </Box>
        );
      case 5:
        return (
          <Box sx={{ p: 3 }}>
            <Typography variant="h6" gutterBottom sx={{ textAlign: 'center', mb: 3 }}>
              Which veterinary products did you use last year? (You can select multiple)
            </Typography>
            
            <Box sx={{ mb: 3 }}>
              <Grid container spacing={1} sx={{ mb: 2 }}>
                <Grid item>
                  <Button
                    variant={selectedLetter === 'All' ? 'contained' : 'outlined'}
                    onClick={() => setSelectedLetter('All')}
                    sx={{ minWidth: '40px' }}
                  >
                    All
                  </Button>
                </Grid>
                {Array.from('ABCDEFGHIJKLMNOPQRSTUVWXYZ').map((letter) => {
                  // Comprobar si hay productos que empiezan con esta letra
                  const hasProducts = Object.keys(treatmentInfo).some(
                    name => name.startsWith(letter)
                  );
                  
                  return (
                    <Grid item key={letter}>
                      <Button
                        variant={selectedLetter === letter ? 'contained' : 'outlined'}
                        onClick={() => setSelectedLetter(letter)}
                        sx={{ 
                          minWidth: '40px',
                          opacity: hasProducts ? 1 : 0.5,
                          pointerEvents: hasProducts ? 'auto' : 'none'
                        }}
                        disabled={!hasProducts}
                      >
                        {letter}
                      </Button>
                    </Grid>
                  );
                })}
              </Grid>
            </Box>

            <Grid container spacing={2}>
              {Object.entries(treatmentInfo)
                .filter(([name]) => 
                  selectedLetter === 'All' || (selectedLetter && name.startsWith(selectedLetter))
                )
                .map(([product]) => (
                  <Fade 
                    in={true} 
                    style={{ transitionDelay: '100ms' }}
                    key={product}
                  >
                    <Grid item xs={12} sm={6} md={3} key={product}>
                      <StyledCard sx={{ 
                        height: '100%',
                        display: 'flex',
                        flexDirection: 'column',
                        justifyContent: 'space-between'
                      }}>
                        <CardContent>
                          <Box sx={{ display: 'flex', alignItems: 'center', mb: 2 }}>
                            <Checkbox
                              checked={state.veterinaryProducts.includes(product)}
                              onChange={(e) => {
                                const newProducts = e.target.checked
                                  ? [...state.veterinaryProducts, product]
                                  : state.veterinaryProducts.filter(p => p !== product);
                                handleInputChange('veterinaryProducts', newProducts);
                              }}
                            />
                            <Typography>{product}</Typography>
                          </Box>
                          <Button
                            variant="outlined"
                            startIcon={<InfoIcon />}
                            onClick={() => {
                              setSelectedProduct(product);
                              setDialogOpen(true);
                            }}
                            fullWidth
                          >
                            Read More
                          </Button>
                        </CardContent>
                      </StyledCard>
                    </Grid>
                  </Fade>
                ))}
            </Grid>

            <Dialog
              open={dialogOpen}
              onClose={() => setDialogOpen(false)}
              maxWidth="sm"
              fullWidth
            >
              {selectedProduct && treatmentInfo[selectedProduct] && (
                <>
                  <DialogTitle>{selectedProduct}</DialogTitle>
                  <DialogContent>
                    <Typography variant="subtitle1" gutterBottom>
                      Type: {treatmentInfo[selectedProduct].type}
                    </Typography>
                    <Typography paragraph>
                      {treatmentInfo[selectedProduct].description}
                    </Typography>
                    <Typography variant="subtitle1" gutterBottom>
                      Usage Instructions:
                    </Typography>
                    <Typography paragraph>
                      {treatmentInfo[selectedProduct].usage}
                    </Typography>
                    <Typography variant="body2" color="text.secondary">
                      Source: <Link href={treatmentInfo[selectedProduct].source} target="_blank" rel="noopener">
                        Official Documentation
                      </Link>
                    </Typography>
                  </DialogContent>
                  <DialogActions>
                    <Button onClick={() => setDialogOpen(false)}>Close</Button>
                  </DialogActions>
                </>
              )}
            </Dialog>
          </Box>
        );
      default:
        return null;
    }
  };

  const getStepContent = (step: number) => {
    const content = renderStep();
    return (
      <Fade in={true} timeout={400}>
        <Box>{content}</Box>
      </Fade>
    );
  };

  const getTreatmentSeason = (month: number) => {
    if (month <= 1 || month === 11) return SEASONS.WINTER; 
    if (month >= 2 && month <= 4) return SEASONS.SPRING; 
    if (month >= 5 && month <= 7) return SEASONS.SUMMER; 
    return SEASONS.AUTUMN; 
  };

  const currentMonth = new Date().getMonth();

  return (
    <Box sx={{ display: 'flex', flexDirection: 'column', margin: 0, padding: 0, pb: 12, minHeight: '100vh' }}>
      <HeroSection>
        <Container maxWidth="md">
          <HeroContent>
            <Typography variant="h2" component="h1" gutterBottom>
              Virtual Varrometer
            </Typography>
            <Typography variant="h5" paragraph>
              Your Advanced Diagnostic Tool for Varroa Control
            </Typography>
            <Typography variant="body1" sx={{ mb: 4, maxWidth: '800px', mx: 'auto' }}>
              Follow our step-by-step guide to assess your colony's health and receive 
              personalized treatment recommendations.
            </Typography>
          </HeroContent>
        </Container>
      </HeroSection>

      <Container maxWidth="lg" sx={{ p: 3 }}>
        <Stepper activeStep={activeStep} alternativeLabel sx={{ mb: 4 }}>
          {steps.map((step) => (
            <Step key={step.id}>
              <StepLabel
                StepIconComponent={() => (
                  <Box sx={{ 
                    width: 40, 
                    height: 40, 
                    borderRadius: '50%',
                    bgcolor: activeStep === steps.indexOf(step) ? 'primary.main' : 'grey.300',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    color: activeStep === steps.indexOf(step) ? 'white' : 'grey.700'
                  }}>
                    {step.icon}
                  </Box>
                )}
              >
                {step.label}
              </StepLabel>
            </Step>
          ))}
        </Stepper>

        <Box sx={{ position: 'relative', minHeight: '60vh' }}>
          <Slide direction={slideDirection} in={true} mountOnEnter unmountOnExit timeout={300}>
            <Box>
              <Fade in={true} timeout={400}>
                <Box>
                  {getStepContent(activeStep)}
                </Box>
              </Fade>
            </Box>
          </Slide>
        </Box>

        <Box sx={{ display: 'flex', justifyContent: 'space-between', mt: 4, pb: 4 }}>
          <Button
            onClick={handleBack}
            disabled={activeStep === 0}
          >
            Back
          </Button>
          <Button
            variant="contained"
            onClick={handleNext}
            disabled={!canContinue()}
          >
            {activeStep === steps.length - 1 ? 'Finish' : 'Next'}
          </Button>
        </Box>
      </Container>
    </Box>
  );
};

export default Introduction;
