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, ColonyStrength } from '../../../types/varrometer';
import { beekeepingOptions, timeOptions, hiveOptions } 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,
  styled,
  SelectChangeEvent
} 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';

const HeroSection = styled(Box)(({ theme }) => ({
  position: 'relative',
  color: 'white',
  minHeight: '10vh',
  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: '10px'
});

interface State {
  frames: number;
  actionTime: string;
  bottomBoard: string;
  veterinaryProducts: string[];
}

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

const frameOptions = Array.from({ length: 10 }, (_, 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 bottomBoardOptions = [
  {
    value: 'solid',
    label: 'Solid Bottom Board',
    description: 'Traditional solid bottom board for better colony warmth'
  },
  {
    value: 'screened',
    label: 'Screened Bottom Board',
    description: 'Allows better ventilation and natural mite drop'
  }
];

const Introduction: React.FC = () => {
  const dispatch = useDispatch();
  const { beekeepingType, timePerHive, hiveType, reference, assessmentDate } = useSelector((state: RootState) => state.varrometer);
  const [activeStep, setActiveStep] = React.useState(0);
  const [state, setState] = useState<State>({
    frames: 1,
    actionTime: '',
    bottomBoard: 'solid',
    veterinaryProducts: []
  });

  const today = new Date().toISOString().split('T')[0];

  useEffect(() => {
    if (!assessmentDate) {
      dispatch(updateVarrometerState({ assessmentDate: today }));
    }
  }, [dispatch, assessmentDate]);

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

  const handleFramesChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const newFrames = parseInt(event.target.value);
    setState(prev => ({ ...prev, frames: newFrames }));
    dispatch(updateVarrometerState({ 
      frames: newFrames,
      colonyStrength: calculateColonyStrength(newFrames)
    }));
  };

  const steps = [
    { label: 'Assessment Info', icon: <AssignmentIcon /> },
    { label: 'Beekeeping Type', icon: <NatureIcon /> },
    { label: 'Time Available', icon: <AccessTimeIcon /> },
    { label: 'Hive Type', icon: <HomeIcon /> },
    { label: 'Number of Frames', icon: <ViewModuleIcon /> },
    { label: 'Action Time', icon: <CalendarTodayIcon /> },
    { label: 'Bottom Board Type', icon: <ViewInArIcon /> },
    { label: 'Previous Treatment', icon: <MedicationIcon /> }
  ];

  const handleNext = () => {
    dispatch(updateVarrometerState({
      frames: state.frames,
      actionTime: state.actionTime,
      bottomBoard: state.bottomBoard,
      veterinaryProducts: state.veterinaryProducts,
      currentPhase: 'surveillance'
    }));
    setActiveStep((prevStep) => prevStep + 1);
  };

  const handleBack = () => {
    setActiveStep((prevStep) => prevStep - 1);
  };

  const handleBeekeepingTypeSelect = (value: BeekeepingType) => {
    dispatch(updateVarrometerState({ beekeepingType: value }));
    handleNext();
  };

  const handleTimeSelect = (value: TimePerHive) => {
    dispatch(updateVarrometerState({ timePerHive: value }));
    handleNext();
  };

  const handleHiveTypeSelect = (value: HiveType) => {
    dispatch(updateVarrometerState({ hiveType: value }));
    handleNext();
  };

  const handleActionTimeChange = (event: SelectChangeEvent) => {
    setState(prev => ({ ...prev, actionTime: event.target.value }));
  };

  const handleBottomBoardChange = (event: SelectChangeEvent) => {
    setState(prev => ({ ...prev, bottomBoard: event.target.value }));
  };

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

  const handleVeterinaryProductsChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const products = event.target.value ? event.target.value.split(',').map(p => p.trim()) : [];
    setState(prev => ({ ...prev, veterinaryProducts: products }));
  };

  const renderStepContent = (step: number) => {
    switch (step) {
      case 0:
        return (
          <Paper elevation={3} sx={{ p: 3 }}>
            <Grid container spacing={3}>
              <Grid item xs={12} md={6}>
                <TextField
                  label="Reference"
                  value={reference || ''}
                  onChange={(e) => dispatch(updateVarrometerState({ reference: e.target.value }))}
                  fullWidth
                  size="medium"
                  sx={{
                    '& .MuiOutlinedInput-root': {
                      backgroundColor: (theme) => alpha(theme.palette.background.paper, 0.9),
                    }
                  }}
                />
              </Grid>
              <Grid item xs={12} md={6}>
                <TextField
                  label="Assessment Date"
                  type="date"
                  value={assessmentDate || today}
                  onChange={(e) => dispatch(updateVarrometerState({ assessmentDate: e.target.value }))}
                  fullWidth
                  InputLabelProps={{ shrink: true }}
                  sx={{
                    '& .MuiOutlinedInput-root': {
                      backgroundColor: (theme) => alpha(theme.palette.background.paper, 0.9),
                    }
                  }}
                />
              </Grid>
            </Grid>
          </Paper>
        );
      case 1:
        return (
          <Grid container spacing={2}>
            {beekeepingOptions.map((option) => (
              <Grid item xs={12} sm={6} md={4} key={option.value}>
                <Card 
                  sx={{ 
                    height: '100%',
                    transition: '0.3s',
                    '&:hover': {
                      transform: 'translateY(-4px)',
                      boxShadow: 6
                    },
                    ...(beekeepingType === option.value && {
                      outline: '2px solid',
                      outlineColor: 'primary.main',
                      bgcolor: (theme) => alpha(theme.palette.primary.main, 0.05)
                    })
                  }}
                >
                  <CardActionArea 
                    onClick={() => handleBeekeepingTypeSelect(option.value as BeekeepingType)}
                    sx={{ height: '100%' }}
                  >
                    <CardContent>
                      <Typography gutterBottom variant="h6" component="div">
                        {option.label}
                      </Typography>
                      <Typography variant="body2" color="text.secondary">
                        {option.description}
                      </Typography>
                    </CardContent>
                  </CardActionArea>
                </Card>
              </Grid>
            ))}
          </Grid>
        );
      case 2:
        return (
          <Grid container spacing={2}>
            {timeOptions.map((option) => (
              <Grid item xs={12} sm={6} md={4} key={option.value}>
                <Card 
                  sx={{ 
                    height: '100%',
                    transition: '0.3s',
                    '&:hover': {
                      transform: 'translateY(-4px)',
                      boxShadow: 6
                    },
                    ...(timePerHive === option.value && {
                      outline: '2px solid',
                      outlineColor: 'primary.main',
                      bgcolor: (theme) => alpha(theme.palette.primary.main, 0.05)
                    })
                  }}
                >
                  <CardActionArea 
                    onClick={() => handleTimeSelect(option.value as TimePerHive)}
                    sx={{ height: '100%' }}
                  >
                    <CardContent>
                      <Typography gutterBottom variant="h6" component="div">
                        {option.label}
                      </Typography>
                      <Typography variant="body2" color="text.secondary">
                        {option.description}
                      </Typography>
                    </CardContent>
                  </CardActionArea>
                </Card>
              </Grid>
            ))}
          </Grid>
        );
      case 3:
        return (
          <Grid container spacing={2}>
            {hiveOptions.map((option) => (
              <Grid item xs={12} sm={6} md={4} key={option.value}>
                <Card 
                  sx={{ 
                    height: '100%',
                    transition: '0.3s',
                    '&:hover': {
                      transform: 'translateY(-4px)',
                      boxShadow: 6
                    },
                    ...(hiveType === option.value && {
                      outline: '2px solid',
                      outlineColor: 'primary.main',
                      bgcolor: (theme) => alpha(theme.palette.primary.main, 0.05)
                    })
                  }}
                >
                  <CardActionArea 
                    onClick={() => handleHiveTypeSelect(option.value as HiveType)}
                    sx={{ height: '100%' }}
                  >
                    <CardContent>
                      <Typography gutterBottom variant="h6" component="div">
                        {option.label}
                      </Typography>
                      <Typography variant="body2" color="text.secondary">
                        {option.description}
                      </Typography>
                    </CardContent>
                  </CardActionArea>
                </Card>
              </Grid>
            ))}
          </Grid>
        );
      case 4:
        return (
          <Box>
            <Typography variant="h6" gutterBottom>
              Number of Frames
            </Typography>
            <Typography color="text.secondary" gutterBottom sx={{ mb: 3 }}>
              How many frames of production colony fully covered with bees are there on average per colony?
            </Typography>
            <Grid container spacing={2}>
              <Grid item xs={12}>
                <TextField
                  label="Number of Frames"
                  type="number"
                  value={state.frames}
                  onChange={handleFramesChange}
                  inputProps={{ min: 1, max: 20 }}
                  fullWidth
                />
              </Grid>
            </Grid>
          </Box>
        );
      case 5:
        return (
          <Box>
            <Typography variant="h6" gutterBottom>
              Action Time
            </Typography>
            <Typography color="text.secondary" gutterBottom sx={{ mb: 3 }}>
              When would you like to perform the treatment?
            </Typography>
            <Grid container spacing={2}>
              {actionTimeOptions.map((option) => (
                <Grid item xs={12} sm={6} md={4} lg={3} key={option.value}>
                  <Card 
                    sx={{ 
                      height: '100%',
                      transition: '0.3s',
                      cursor: 'pointer',
                      '&:hover': {
                        transform: 'translateY(-4px)',
                        boxShadow: 6
                      },
                      ...(state.actionTime === option.value && {
                        outline: '2px solid',
                        outlineColor: 'primary.main',
                        bgcolor: (theme) => alpha(theme.palette.primary.main, 0.05)
                      })
                    }}
                    onClick={() => setState(prev => ({ ...prev, actionTime: option.value }))}
                  >
                    <CardMedia
                      component="img"
                      height="140"
                      image={`/images/month-${option.value.toLowerCase()}.png`}
                      alt={option.label}
                      sx={{
                        objectFit: 'contain',
                        p: 2
                      }}
                    />
                    <CardContent>
                      <Typography gutterBottom variant="h6" component="div">
                        {option.label}
                      </Typography>
                      <Typography variant="body2" color="text.secondary">
                        {option.description}
                      </Typography>
                    </CardContent>
                  </Card>
                </Grid>
              ))}
            </Grid>
          </Box>
        );
      case 6:
        return (
          <Box>
            <Typography variant="h6" gutterBottom>
              Bottom Board Type
            </Typography>
            <Typography color="text.secondary" gutterBottom sx={{ mb: 3 }}>
              What type of bottom board do your hives have?
            </Typography>
            <Grid container spacing={2}>
              {bottomBoardOptions.map((option) => (
                <Grid item xs={12} sm={6} md={4} key={option.value}>
                  <Card 
                    sx={{ 
                      height: '100%',
                      transition: '0.3s',
                      cursor: 'pointer',
                      '&:hover': {
                        transform: 'translateY(-4px)',
                        boxShadow: 6
                      },
                      ...(state.bottomBoard === option.value && {
                        outline: '2px solid',
                        outlineColor: 'primary.main',
                        bgcolor: (theme) => alpha(theme.palette.primary.main, 0.05)
                      })
                    }}
                    onClick={() => setState(prev => ({ ...prev, bottomBoard: option.value }))}
                  >
                    <CardMedia
                      component="img"
                      height="140"
                      image={`/images/board-${option.value}.png`}
                      alt={option.label}
                      sx={{
                        objectFit: 'contain',
                        p: 2
                      }}
                    />
                    <CardContent>
                      <Typography gutterBottom variant="h6" component="div">
                        {option.label}
                      </Typography>
                      <Typography variant="body2" color="text.secondary">
                        {option.description}
                      </Typography>
                    </CardContent>
                  </Card>
                </Grid>
              ))}
            </Grid>
          </Box>
        );
      case 7:
        return (
          <Paper elevation={3} sx={{ p: 3 }}>
            <Grid container spacing={3}>
              <Grid item xs={12}>
                <TextField
                  label="Veterinary Products"
                  value={state.veterinaryProducts.join(', ')}
                  onChange={handleVeterinaryProductsChange}
                  fullWidth
                  helperText="Enter products separated by commas"
                />
              </Grid>
            </Grid>
          </Paper>
        );
      default:
        return <div>Unknown step</div>;
    }
  };

  return (
    <Box sx={{ display: 'flex', flexDirection: 'column', margin: 0, padding: 0, pb: 12 }}>
      <HeroSection>
        <HeroContent>
          <Container maxWidth="md">
            <Typography variant="h2" component="h1" gutterBottom>
              Varroa Treatment Assistant
            </Typography>
            <Typography variant="body1" sx={{ mb: 2, maxWidth: '800px', mx: 'auto' }}>
              Let's start by gathering some information about your beekeeping operation
            </Typography>
          </Container>
        </HeroContent>
      </HeroSection>

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

        <Box sx={{ mt: 4, mb: 4 }}>
          {renderStepContent(activeStep)}
        </Box>

        <Box sx={{ display: 'flex', justifyContent: 'flex-end', mt: 4 }}>
          <Button
            disabled={activeStep === 0}
            onClick={handleBack}
            sx={{ mr: 1 }}
          >
            Back
          </Button>
          <Button
            variant="contained"
            onClick={activeStep === steps.length - 1 ? handleComplete : handleNext}
          >
            {activeStep === steps.length - 1 ? 'Start Monitoring' : 'Next'}
          </Button>
        </Box>
      </Container>
    </Box>
  );
};

export default Introduction;
