import React from 'react';
import { Box, Container, Typography, Paper, Grid, Card, CardContent, CardMedia, IconButton, Button, List, ListItem, Stack, Divider, CardActions, TextField } from '@mui/material';
import { styled } from '@mui/material/styles';
import { useMemo, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useDispatch, useSelector } from 'react-redux';
import { RootState } from '../../../store/store';
import { updateVarrometerState } from '../../../store/varrometerSlice';
import { MONITORING_METHODS, MonitoringMethod } from '../../../constants/monitoringMethods';
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';
import InfoIcon from '@mui/icons-material/Info';
import VarroaMeter from '../VarroaMeter';
import MethodInfoDialog from '../MethodInfoDialog';

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

const Surveillance: React.FC = () => {
  const dispatch = useDispatch();
  const state = useSelector((state: RootState) => state.varrometer);
  const { selectedMethod, miteCount, sampleSize, monitoringHistory } = state;
  const [openInfoDialog, setOpenInfoDialog] = React.useState<string | null>(null);
  const navigate = useNavigate();

  const selectedMethodData = MONITORING_METHODS.find(m => m.id === selectedMethod);

  const infestationRate = useMemo(() => {
    if (typeof miteCount === 'number' && typeof sampleSize === 'number' && sampleSize > 0) {
      return (miteCount / sampleSize) * 100;
    }
    return undefined;
  }, [miteCount, sampleSize]);

  const handleMethodSelect = (method: MonitoringMethod) => {
    dispatch(updateVarrometerState({ 
      selectedMethod: method.id,
      miteCount: undefined,
      sampleSize: undefined,
      infestationRate: undefined,
      infestationLevel: undefined
    }));
  };

  const handleMiteCountChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value ? parseInt(e.target.value) : undefined;
    dispatch(updateVarrometerState({ miteCount: value }));
  };

  const handleSampleSizeChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value ? parseInt(e.target.value) : undefined;
    dispatch(updateVarrometerState({ sampleSize: value }));
  };

  const handleContinue = () => {
    if (selectedMethodData && typeof miteCount === 'number' && typeof sampleSize === 'number' && sampleSize > 0) {
      const infestationRate = (miteCount / sampleSize) * 100;
      let infestationLevel: 'green' | 'yellow' | 'red';

      if (infestationRate < selectedMethodData.thresholds.green) {
        infestationLevel = 'green';
      } else if (infestationRate < selectedMethodData.thresholds.yellow) {
        infestationLevel = 'yellow';
      } else {
        infestationLevel = 'red';
      }

      const newHistory = {
        date: new Date().toISOString(),
        method: selectedMethodData.name,
        miteCount,
        sampleSize,
        infestationRate,
        infestationLevel
      };

      dispatch(updateVarrometerState({
        currentPhase: 'methods',
        infestationRate,
        infestationLevel,
        monitoringHistory: [...(monitoringHistory || []), newHistory]
      }));
      navigate('/varrometer/methods');
    }
  };

  const handleBack = () => {
    dispatch(updateVarrometerState({ currentPhase: 'introduction' }));
    navigate('/varrometer/introduction');
  };

  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 Monitoring
            </Typography>
            <Typography variant="body1" sx={{ mb: 2, maxWidth: '800px', mx: 'auto' }}>
              Monitor and assess the level of Varroa infestation in your colonies
            </Typography>
          </Container>
        </HeroContent>
      </HeroSection>

      <Container maxWidth="lg">
        <Box sx={{ mt: 4 }}>
          <Paper elevation={3} sx={{ p: 3, mb: 4, bgcolor: 'primary.main', color: 'white' }}>
            <Typography variant="h5" gutterBottom>
              Varroa Monitoring
            </Typography>
          </Paper>

          {/* Monitoring Methods Cards */}
          <Grid container spacing={3} sx={{ mb: 4 }}>
            {MONITORING_METHODS.map((method) => (
              <Grid item xs={12} md={4} key={method.id}>
                <Card 
                  elevation={method.id === selectedMethod ? 4 : 1}
                  sx={{ 
                    height: '100%',
                    cursor: 'pointer',
                    transition: 'all 0.2s',
                    transform: method.id === selectedMethod ? 'scale(1.02)' : 'scale(1)',
                    '&:hover': {
                      transform: 'scale(1.02)',
                    }
                  }}
                  onClick={() => handleMethodSelect(method)}
                >
                  <CardMedia
                    component="img"
                    height="140"
                    image={`/images/monitoring/${method.id}.jpg`}
                    alt={method.name}
                    sx={{ objectFit: 'cover' }}
                  />
                  <CardContent>
                    <Box sx={{ 
                      display: 'flex', 
                      justifyContent: 'space-between', 
                      alignItems: 'center',
                      mb: 2 
                    }}>
                      <Typography variant="h6" component="div">
                        {method.name}
                      </Typography>
                      <IconButton
                        size="small"
                        onClick={(e) => {
                          e.stopPropagation();
                          setOpenInfoDialog(method.id);
                        }}
                      >
                        <InfoIcon fontSize="small" />
                      </IconButton>
                    </Box>

                    <Box sx={{ 
                      display: 'inline-block',
                      bgcolor: method.accuracy >= 90 ? 'success.light' : method.accuracy >= 70 ? 'warning.light' : 'error.light',
                      px: 1,
                      py: 0.5,
                      borderRadius: 1,
                      mb: 2
                    }}>
                      <Typography variant="body2" sx={{ fontWeight: 'medium' }}>
                        {method.accuracy}% accuracy
                      </Typography>
                    </Box>

                    <Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
                      {method.description}
                    </Typography>

                    {method.id === selectedMethod && (
                      <>
                        <Divider sx={{ my: 2 }} />
                        
                        <Box>
                          <Typography variant="subtitle2" gutterBottom>
                            Implementation:
                          </Typography>
                          <List dense>
                            {method.implementation.map((step, index) => (
                              <ListItem key={index}>{step}</ListItem>
                            ))}
                          </List>
                        </Box>

                        <Box>
                          <Typography variant="subtitle2" gutterBottom>
                            Thresholds:
                          </Typography>
                          <Stack spacing={1}>
                            <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                              <Box sx={{ width: 12, height: 12, bgcolor: '#4caf50', borderRadius: '50%' }} />
                              <Typography variant="body2">Safe: &lt;{method.thresholds.green}%</Typography>
                            </Box>
                            <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                              <Box sx={{ width: 12, height: 12, bgcolor: '#ff9800', borderRadius: '50%' }} />
                              <Typography variant="body2">Warning: {method.thresholds.green}-{method.thresholds.yellow}%</Typography>
                            </Box>
                            <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                              <Box sx={{ width: 12, height: 12, bgcolor: '#f44336', borderRadius: '50%' }} />
                              <Typography variant="body2">Danger: &gt;{method.thresholds.yellow}%</Typography>
                            </Box>
                          </Stack>
                        </Box>
                      </>
                    )}
                  </CardContent>
                  {method.id === selectedMethod && (
                    <CardActions>
                      <Button 
                        size="small" 
                        color="primary"
                        onClick={(e) => {
                          e.stopPropagation();
                          setOpenInfoDialog(method.id);
                        }}
                      >
                        Learn More
                      </Button>
                    </CardActions>
                  )}
                </Card>
              </Grid>
            ))}
          </Grid>

          {/* Results Section - Two Columns */}
          <Grid container spacing={3}>
            {/* Enter Your Results Column */}
            <Grid item xs={12} md={6}>
              <Paper elevation={3} sx={{ p: 3 }}>
                <Typography variant="h6" gutterBottom>
                  Enter Your Results
                </Typography>
                <Stack spacing={3}>
                  <Stack direction="row" spacing={2}>
                    <TextField
                      label="Mite Count"
                      type="number"
                      value={miteCount || ''}
                      onChange={handleMiteCountChange}
                      fullWidth
                    />
                    <TextField
                      label="Sample Size"
                      type="number"
                      value={sampleSize || ''}
                      onChange={handleSampleSizeChange}
                      fullWidth
                      helperText={`Number of ${selectedMethodData?.id.includes('sugar') ? 'bees' : 'cells'} examined`}
                    />
                  </Stack>
                </Stack>
              </Paper>
            </Grid>

            {/* Varroa Infestation Level Column */}
            <Grid item xs={12} md={6}>
              <Paper elevation={3} sx={{ p: 3 }}>
                <Typography variant="h6" gutterBottom>
                  Varroa Infestation Level
                </Typography>
                {typeof infestationRate === 'number' && (
                  <Box sx={{ textAlign: 'center' }}>
                    <VarroaMeter 
                      percentage={infestationRate}
                      greenThreshold={selectedMethodData?.thresholds.green || 0}
                      yellowThreshold={selectedMethodData?.thresholds.yellow || 0}
                    />
                  </Box>
                )}
              </Paper>
            </Grid>
          </Grid>

          <Stack direction="row" spacing={2} justifyContent="flex-end" sx={{ mt: 4 }}>
            <Button onClick={handleBack}>
              Back
            </Button>
            <Button
              variant="contained"
              onClick={handleContinue}
              disabled={!selectedMethod || typeof miteCount !== 'number' || typeof sampleSize !== 'number' || sampleSize <= 0}
            >
              Continue
            </Button>
          </Stack>
        </Box>

        <MethodInfoDialog
          method={openInfoDialog ? MONITORING_METHODS.find(m => m.id === openInfoDialog) : undefined}
          open={!!openInfoDialog}
          onClose={() => setOpenInfoDialog(null)}
        />
      </Container>
    </Box>
  );
};

export default Surveillance;
