import React, { useMemo } from 'react';
import { 
  Box, 
  Container, 
  Typography, 
  Paper,
  Grid, 
  Button, 
  List, 
  ListItem, 
  Stack, 
  Divider, 
  TextField,
  Alert
} from '@mui/material';
import { styled } from '@mui/material/styles';
import { useDispatch, useSelector } from 'react-redux';
import { RootState } from '../../../store/store';
import { updateVarrometerState } from '../../../store/varrometerSlice';
import { MONITORING_METHODS } from '../../../constants/monitoringMethods';
import VarroaMeter from '../VarroaMeter';

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 DataEntry: React.FC = () => {
  const dispatch = useDispatch();
  const state = useSelector((state: RootState) => state.varrometer);
  const { selectedMethod, miteCount, sampleSize, monitoringHistory } = state;

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

  const infestationRate = useMemo(() => {
    if (typeof miteCount === 'number' && typeof sampleSize === 'number' && sampleSize > 0) {
      // Calculate the value based on the measurement type
      let infestationRate: number;
      
      if (selectedMethodData?.measurementType === 'percentage') {
        // For percentage-based methods (Sugar Roll, Alcohol Wash)
        infestationRate = (miteCount / sampleSize) * 100;
      } else {
        // For daily count methods (Sticky Board)
        infestationRate = miteCount / sampleSize; // mites per day
      }
      
      return infestationRate;
    }
    return undefined;
  }, [miteCount, sampleSize, selectedMethodData]);

  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 handleBack = () => {
    dispatch(updateVarrometerState({ currentPhase: 'surveillance' }));
  };

  const handleSubmit = () => {
    if (selectedMethod && typeof infestationRate === 'number' && typeof miteCount === 'number' && typeof sampleSize === 'number') {
      let infestationLevel: 'green' | 'yellow' | 'red' = 'green';
      
      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,
        measurementType: selectedMethodData!.measurementType
      };

      dispatch(updateVarrometerState({
        currentPhase: 'introduction',
        infestationRate,
        infestationLevel,
        monitoringHistory: [...(monitoringHistory || []), newHistory],
        selectedBiotechnicalMethods: []
      }));
    }
  };

  // Función para obtener el mensaje de recomendación basado en el nivel de infestación
  const getRecommendationMessage = () => {
    if (typeof infestationRate !== 'number' || !selectedMethodData) return null;

    if (infestationRate < selectedMethodData.thresholds.green) {
      return {
        severity: 'success',
        title: 'CONGRATULATIONS! NO ACTION IS REQUIRED IN THE SHORT TERM',
        message: 'Consider continuing to monitor the varroa infestation level. You can maintain low levels of varroa by using bio-technical methods, such as cutting Drone Traps/Combs every month. We recommend continuing to the next screens to save this test in your "My History" section for future reference.'
      };
    } else if (infestationRate < selectedMethodData.thresholds.yellow) {
      return {
        severity: 'warning',
        title: 'ATTENTION! VARROA INFESTATION LEVEL OF CONCERN!',
        message: 'Consider taking varroa control measures within the next 3 weeks. Continue to the next steps to discover the most adapted strategy to your reality.'
      };
    } else {
      return {
        severity: 'error',
        title: 'ATTENTION! VARROA INFESTATION LEVEL THREATENING COLONY SURVIVAL!',
        message: 'Consider taking urgent varroa control measures (within a week). Continue to the next steps to find the most appropriate treatment.'
      };
    }
  };

  const recommendationMessage = getRecommendationMessage();

  return (
    <Box sx={{ display: 'flex', flexDirection: 'column', margin: 0, padding: 0, pb: 12 }}>
      <HeroSection>
        <HeroContent>
          <Container maxWidth="lg">
            <Typography variant="h5" component="h1">
              Varrometer
            </Typography>
            <Typography variant="body2" sx={{ fontSize: '0.85rem' }}>
              Monitor and control varroa mite infestations in your beehives
            </Typography>
          </Container>
        </HeroContent>
      </HeroSection>

      <Container maxWidth="lg" sx={{ mt: 2, mb: 2 }}>
        <Box sx={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
          {/* Main Content */}
          <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 2 }}>
            {/* Left Column (1/3 width) - Method Details */}
            <Box sx={{ flex: '1 1 150px', minWidth: '150px' }}>
              <Paper 
                elevation={1} 
                sx={{ 
                  p: 2, 
                  height: '100%', 
                  display: 'flex', 
                  flexDirection: 'column',
                  minHeight: '200px'
                }}
              >
                <Typography variant="h6" gutterBottom>
                  {selectedMethodData?.name || 'Monitoring Method'} - Implementation Details
                </Typography>
                
                {selectedMethodData && (
                  <Box sx={{ flexGrow: 1 }}>
                    <Typography variant="subtitle2" sx={{ mb: 1 }}>
                      Implementation:
                    </Typography>
                    <List dense disablePadding>
                      {selectedMethodData.implementation.map((step, index) => (
                        <ListItem key={index} sx={{ py: 0.5 }}>
                          <Typography variant="body2" sx={{ color: 'text.primary' }}>
                            <span style={{ color: 'primary.main', fontWeight: 'bold', marginRight: '4px' }}>
                              {index + 1}.
                            </span>
                            {step}
                          </Typography>
                        </ListItem>
                      ))}
                    </List>

                    <Typography variant="subtitle2" sx={{ mt: 2, mb: 1 }}>
                      Thresholds:
                    </Typography>
                    <Stack direction="column" spacing={1}>
                      <Box sx={{ display: 'flex', alignItems: 'center' }}>
                        <Box
                          sx={{
                            width: 12,
                            height: 12,
                            borderRadius: '50%',
                            bgcolor: 'success.main',
                            mr: 1,
                          }}
                        />
                        <Typography variant="body2">
                          Safe: &lt;{selectedMethodData.thresholds.green}%
                        </Typography>
                      </Box>
                      <Box sx={{ display: 'flex', alignItems: 'center' }}>
                        <Box
                          sx={{
                            width: 12,
                            height: 12,
                            borderRadius: '50%',
                            bgcolor: 'warning.main',
                            mr: 1,
                          }}
                        />
                        <Typography variant="body2">
                          Warning: {selectedMethodData.thresholds.green}-{selectedMethodData.thresholds.yellow}%
                        </Typography>
                      </Box>
                      <Box sx={{ display: 'flex', alignItems: 'center' }}>
                        <Box
                          sx={{
                            width: 12,
                            height: 12,
                            borderRadius: '50%',
                            bgcolor: 'error.main',
                            mr: 1,
                          }}
                        />
                        <Typography variant="body2">
                          Danger: &gt;{selectedMethodData.thresholds.yellow}%
                        </Typography>
                      </Box>
                    </Stack>
                  </Box>
                )}
              </Paper>
            </Box>
            
            {/* Right Column (2/3 width) - Results Entry and Infestation Level */}
            <Box sx={{ flex: '2 1 600px', display: 'flex', flexWrap: 'wrap', gap: 2 }}>
              {/* Enter Your Results Section */}
              <Box sx={{ flex: '1 1 300px', minWidth: '280px' }}>
                <Paper 
                  elevation={1} 
                  sx={{ 
                    p: 2, 
                    height: '100%', 
                    display: 'flex', 
                    flexDirection: 'column',
                    minHeight: '200px'
                  }}
                >
                  <Typography variant="h6" gutterBottom>
                    Enter Your Results
                  </Typography>
                  
                  {/* Recommendations Section - Moved to the top */}
                  {infestationRate !== undefined && recommendationMessage && (
                    <Alert 
                      severity={recommendationMessage.severity as 'success' | 'warning' | 'error'} 
                      sx={{ p: 1.5, mb: 2 }}
                      icon={<Box sx={{ mt: 0.5 }}>{recommendationMessage.severity === 'success' ? '✓' : '!'}</Box>}
                    >
                      <Typography variant="subtitle2" sx={{ fontWeight: 'bold' }}>
                        {recommendationMessage.title}
                      </Typography>
                      <Typography variant="body2">
                        {recommendationMessage.message}
                      </Typography>
                    </Alert>
                  )}
                  
                  <Stack spacing={2} sx={{ mb: 2 }}>
                    <TextField
                      label={selectedMethodData?.countLabel || "Mite Count"}
                      type="number"
                      value={miteCount || ''}
                      onChange={handleMiteCountChange}
                      fullWidth
                      size="small"
                    />
                    <TextField
                      label={selectedMethodData?.sampleSizeLabel || "Sample Size"}
                      type="number"
                      value={sampleSize || ''}
                      onChange={handleSampleSizeChange}
                      helperText={selectedMethodData?.measurementType === 'daily-count' 
                        ? "Number of days monitored" 
                        : "Number of bees in sample"}
                      fullWidth
                      size="small"
                    />
                  </Stack>
                  
                  {/* Action Button at the bottom */}
                  <Box sx={{ mt: 'auto' }}>
                    {infestationRate !== undefined && recommendationMessage && (
                      <Box sx={{ display: 'flex', justifyContent: 'center' }}>
                        {recommendationMessage.severity === 'success' && (
                          <Button 
                            variant="contained" 
                            color="success"
                            onClick={handleSubmit}
                            size="small"
                          >
                            Yes, i want to save this data. Continue with the test
                          </Button>
                        )}
                        {recommendationMessage.severity !== 'success' && (
                          <Button 
                            variant="contained" 
                            color={recommendationMessage.severity === 'warning' ? 'warning' : 'error'}
                            onClick={handleSubmit}
                            size="small"
                          >
                            Continue to Treatment
                          </Button>
                        )}
                      </Box>
                    )}
                  </Box>
                </Paper>
              </Box>
              
              {/* Varroa Infestation Level Section */}
              <Box sx={{ flex: '1 1 300px', minWidth: '280px' }}>
                <Paper 
                  elevation={1} 
                  sx={{ 
                    p: 2, 
                    height: '100%', 
                    display: 'flex', 
                    flexDirection: 'column',
                    minHeight: '200px'
                  }}
                >
                  <Typography variant="h6" gutterBottom>
                    Varroa Infestation Level
                  </Typography>
                  <Box sx={{ 
                    display: 'flex', 
                    flexDirection: 'column', 
                    alignItems: 'center', 
                    justifyContent: 'center', 
                    flexGrow: 1 
                  }}>
                    {infestationRate !== undefined ? (
                      <VarroaMeter 
                        value={infestationRate} 
                        greenThreshold={selectedMethodData?.thresholds.green || 3}
                        yellowThreshold={selectedMethodData?.thresholds.yellow || 5}
                        measurementType={selectedMethodData?.measurementType || 'percentage'}
                        unit={selectedMethodData?.resultUnit || '%'}
                      />
                    ) : (
                      <Typography variant="body2" color="text.secondary" align="center">
                        Enter mite count and sample size to see results
                      </Typography>
                    )}
                  </Box>
                </Paper>
              </Box>
            </Box>
          </Box>

          {/* Navigation Buttons */}
          <Stack direction="row" spacing={2} justifyContent="flex-end">
            <Button onClick={handleBack}>
              Back
            </Button>
          </Stack>
        </Box>
      </Container>
    </Box>
  );
};

export default DataEntry;
