import { useState, useEffect } from 'react';
import { createTheme, CssBaseline, ThemeProvider, Typography, Button, Box, CircularProgress, Select, MenuItem, FormControl, InputLabel, FormControlLabel, Checkbox, Alert } from '@mui/material';
import { GCDTable } from './components/GCDTable';
import { getNextInteger, getPreviousInteger, getInitialIntegerForViewport, INTEGERS } from './utils/integerUtils';

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

function App() {
  const [currentInteger, setCurrentInteger] = useState(() => getInitialIntegerForViewport());
  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 handleNextInteger = () => {
    setCurrentInteger(prev => getNextInteger(prev));
  };
  
  const handlePreviousInteger = () => {
    setCurrentInteger(prev => getPreviousInteger(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>
            GCD Table
          </Typography>
          
          <Box>
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 2, mb: 1 }}>
              {isComputing && <CircularProgress size={20} />}
            </Box>
            <Typography variant="body2" color="text.secondary" paragraph>
              Log GCD table for integers 1 to {currentInteger}
            </Typography>
            <Typography variant="body2" color="text.secondary" paragraph>
              Showing ({currentInteger} × {currentInteger}) grid
            </Typography>
            <FormControl fullWidth sx={{ mb: 2 }}>
              <InputLabel id="integer-select-label">Select Size</InputLabel>
              <Select
                labelId="integer-select-label"
                id="integer-select"
                value={currentInteger}
                label="Select Integer"
                onChange={(e) => setCurrentInteger(e.target.value as number)}
              >
                {INTEGERS.map((integer) => (
                  <MenuItem key={integer} value={integer}>
                    {integer}
                  </MenuItem>
                ))}
              </Select>
            </FormControl>
            <Box sx={{ display: 'flex', gap: 1 }}>
              <Button 
                variant="outlined" 
                onClick={handlePreviousInteger}
                fullWidth
                disabled={currentInteger === INTEGERS[0]}
              >
                Previous
              </Button>
              <Button 
                variant="contained" 
                onClick={handleNextInteger}
                fullWidth
                disabled={currentInteger === INTEGERS[INTEGERS.length - 1]}
              >
                Next
              </Button>
            </Box>
          </Box>
          
          <Box sx={{ mt: 2 }}>
            <Typography variant="body2" color="text.secondary">
              Each cell (i, j) shows the value of log(gcd(i, j))
            </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
        }}>
          <GCDTable 
            n={currentInteger} 
            onLoadingChange={setIsComputing}
            showColorBar={showColorBar}
          />
        </Box>
      </Box>
    </ThemeProvider>
  );
}

export default App;
