import { useState, useEffect } from 'react';
import { createTheme, CssBaseline, ThemeProvider, Typography, Button, Box, CircularProgress, Select, MenuItem, FormControl, InputLabel, FormControlLabel, Checkbox, Alert } from '@mui/material';
import { MultiplicationTable } from './components/MultiplicationTable';
import { getNextPrime, getPreviousPrime, getInitialPrimeForViewport, PRIMES } from './utils/primeUtils';

const theme = createTheme({
  palette: {
    mode: 'light',
    primary: {
      main: '#1976d2',
    },
  },
});

function App() {
  const [currentPrime, setCurrentPrime] = useState(() => getInitialPrimeForViewport());
  const [isComputing, setIsComputing] = useState(true);
  const [showColorBar, setShowColorBar] = useState(false);
  const [isMobile, setIsMobile] = useState(false);
  
  // Detect mobile device
  useEffect(() => {
    const checkMobile = () => {
      const isMobileDevice = window.innerWidth < 768; // Standard tablet/mobile breakpoint
      setIsMobile(isMobileDevice);
    };
    
    checkMobile();
    window.addEventListener('resize', checkMobile);
    
    return () => window.removeEventListener('resize', checkMobile);
  }, []);
  
  const handleNextPrime = () => {
    setCurrentPrime(prev => getNextPrime(prev));
  };
  
  const handlePreviousPrime = () => {
    setCurrentPrime(prev => getPreviousPrime(prev));
  };
  
  return (
    <ThemeProvider theme={theme}>
      <CssBaseline />
      <Box sx={{ 
        display: 'flex', 
        flexDirection: { xs: 'column', md: 'row' },
        height: '100vh', 
        overflow: 'hidden' 
      }}>
        {/* Sidebar with controls */}
        <Box sx={{ 
          width: { xs: '100%', md: 300 },
          maxHeight: { xs: 'auto', md: '100vh' },
          p: { xs: 2, md: 3 },
          borderRight: { xs: 0, md: 1 },
          borderBottom: { xs: 1, md: 0 },
          borderColor: 'divider',
          display: 'flex',
          flexDirection: 'column',
          gap: 2,
          overflowY: { xs: 'visible', md: 'auto' }
        }}>
          <Typography variant="h5" component="h1" gutterBottom>
            Finite Field Multiplication Table
          </Typography>
          
          <Box>
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 2, mb: 1 }}>
              <Typography variant="h6" component="h2">
                Prime: {currentPrime}
              </Typography>
              {isComputing && <CircularProgress size={20} />}
            </Box>
            <Typography variant="body2" color="text.secondary" paragraph>
              Multiplication table modulo {currentPrime}
            </Typography>
            <Typography variant="body2" color="text.secondary" paragraph>
              Showing ({currentPrime - 1} × {currentPrime - 1}) grid
            </Typography>
            <FormControl fullWidth sx={{ mb: 2 }}>
              <InputLabel id="prime-select-label">Select Prime</InputLabel>
              <Select
                labelId="prime-select-label"
                id="prime-select"
                value={currentPrime}
                label="Select Prime"
                onChange={(e) => setCurrentPrime(e.target.value as number)}
              >
                {PRIMES.map((prime) => (
                  <MenuItem key={prime} value={prime}>
                    {prime}
                  </MenuItem>
                ))}
              </Select>
            </FormControl>
            <Box sx={{ display: 'flex', gap: 1 }}>
              <Button 
                variant="outlined" 
                onClick={handlePreviousPrime}
                fullWidth
                disabled={currentPrime === PRIMES[0]}
              >
                Previous
              </Button>
              <Button 
                variant="contained" 
                onClick={handleNextPrime}
                fullWidth
                disabled={currentPrime === PRIMES[PRIMES.length - 1]}
              >
                Next
              </Button>
            </Box>
          </Box>
          
          <Box sx={{ mt: 2 }}>
            <Typography variant="body2" color="text.secondary">
              Each cell (i, j) shows the value of (i × j) mod {currentPrime}
            </Typography>
          </Box>
          
          {isMobile ? (
            <Box sx={{ mt: 2 }}>
              <Alert severity="info" sx={{ fontSize: '0.875rem' }}>
                This visualization is best viewed on a desktop.
              </Alert>
            </Box>
          ) : (
            <Box sx={{ mt: 2 }}>
              <FormControlLabel
                control={
                  <Checkbox
                    checked={showColorBar}
                    onChange={(e) => setShowColorBar(e.target.checked)}
                  />
                }
                label="Show Color Bar"
              />
            </Box>
          )}
        </Box>
        
        {/* Main content area */}
        <Box sx={{ 
          flex: 1, 
          display: 'flex', 
          alignItems: 'center', 
          justifyContent: 'center',
          p: { xs: 1, md: 2 },
          overflow: 'hidden',
          minHeight: 0
        }}>
          <MultiplicationTable 
            prime={currentPrime} 
            onLoadingChange={setIsComputing}
            showColorBar={showColorBar}
          />
        </Box>
      </Box>
    </ThemeProvider>
  );
}

export default App;
