import Grid from '@mui/material/Grid';
import Button from '@mui/material/Button';
import Typography from '@mui/material/Typography';
import Box from '@mui/material/Box';
import { SpeakButton } from '../common/SpeakButton';
import type { MultipleChoiceExercise } from '../../types/lesson';

interface MultipleChoiceProps {
  exercise: MultipleChoiceExercise;
  selectedAnswer: number | null;
  isChecked: boolean;
  isCorrect: boolean | null;
  onSelect: (index: number) => void;
}

export function MultipleChoice({
  exercise,
  selectedAnswer,
  isChecked,
  isCorrect,
  onSelect,
}: MultipleChoiceProps) {
  function getButtonVariant(index: number) {
    if (!isChecked) {
      return index === selectedAnswer ? 'contained' : 'outlined';
    }
    if (index === exercise.correctIndex) return 'contained';
    if (index === selectedAnswer && !isCorrect) return 'contained';
    return 'outlined';
  }

  function getButtonColor(index: number) {
    if (!isChecked) {
      return index === selectedAnswer ? 'secondary' : 'inherit';
    }
    if (index === exercise.correctIndex) return 'primary';
    if (index === selectedAnswer && !isCorrect) return 'error';
    return 'inherit';
  }

  return (
    <Box sx={{ width: '100%', maxWidth: 500, mx: 'auto' }}>
      <Box
        sx={{
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          gap: 1.5,
          mb: 4,
        }}
      >
        {exercise.promptAudio && <SpeakButton text={exercise.audioText ?? exercise.prompt} />}
        <Typography variant="h5" sx={{ textAlign: 'center' }}>
          {exercise.prompt}
        </Typography>
      </Box>

      <Grid container spacing={2}>
        {exercise.choices.map((choice, index) => (
          <Grid size={{ xs: 6 }} key={index}>
            <Button
              fullWidth
              variant={getButtonVariant(index)}
              color={getButtonColor(index) as 'primary' | 'secondary' | 'error' | 'inherit'}
              onClick={() => onSelect(index)}
              disabled={isChecked}
              sx={{
                py: 2,
                fontSize: '1rem',
                textTransform: 'none',
                borderColor: 'rgba(255,255,255,0.2)',
                '&.MuiButton-outlined': {
                  boxShadow: '0 4px 0 rgba(255,255,255,0.1)',
                  '&:active': {
                    boxShadow: '0 1px 0 rgba(255,255,255,0.1)',
                    transform: 'translateY(3px)',
                  },
                },
              }}
            >
              {choice}
            </Button>
          </Grid>
        ))}
      </Grid>
    </Box>
  );
}
