import { useState, useEffect, useRef } from 'react';
import { Box, Paper } from '@mui/material';
import { ThemeProvider, createTheme } from '@mui/material/styles';
import CssBaseline from '@mui/material/CssBaseline';
import AppBar from './components/AppBar';
import ProofEditor from './components/ProofEditor';
import ResultsPanel from './components/ResultsPanel';
import { verifyProofContent } from './utils/verification';
import type { VerificationResult } from './utils/verification';
import { getContentFromUrl, updateUrlWithContent } from './utils/urlState';

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

const DEFAULT_EXAMPLE = `axiom my_axiom
    suppose a : Nat
    conclude eq(a, a)

theorem reflexivity
    suppose x : Nat
    conclude eq(x, x)
    proof
        exact my_axiom
`;

function App() {
  // Load content from URL on mount using lazy initialization
  const [content, setContent] = useState<string>(() => {
    const urlContent = getContentFromUrl();
    return urlContent || DEFAULT_EXAMPLE;
  });
  const [verificationResult, setVerificationResult] = useState<VerificationResult | null>(null);
  const [isVerifying, setIsVerifying] = useState(false);
  const verificationTimeoutRef = useRef<number | null>(null);
  const urlUpdateTimeoutRef = useRef<number | null>(null);

  // Debounced verification
  useEffect(() => {
    if (verificationTimeoutRef.current) {
      clearTimeout(verificationTimeoutRef.current);
    }

    const contentToVerify = content.trim();

    verificationTimeoutRef.current = window.setTimeout(() => {
      if (!contentToVerify) {
        setVerificationResult(null);
        setIsVerifying(false);
      } else {
        setIsVerifying(true);
        const result = verifyProofContent(contentToVerify);
        setVerificationResult(result);
        setIsVerifying(false);
      }
    }, 500); // 500ms debounce

    return () => {
      if (verificationTimeoutRef.current) {
        clearTimeout(verificationTimeoutRef.current);
      }
    };
  }, [content]);

  // Debounced URL update
  useEffect(() => {
    if (urlUpdateTimeoutRef.current) {
      clearTimeout(urlUpdateTimeoutRef.current);
    }

    urlUpdateTimeoutRef.current = window.setTimeout(() => {
      updateUrlWithContent(content);
    }, 1000); // 1 second debounce for URL updates

    return () => {
      if (urlUpdateTimeoutRef.current) {
        clearTimeout(urlUpdateTimeoutRef.current);
      }
    };
  }, [content]);

  const handleDownload = () => {
    const blob = new Blob([content], { type: 'text/plain' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = 'proof.prf';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
  };

  return (
    <ThemeProvider theme={theme}>
      <CssBaseline />
      <Box sx={{ height: '100vh', display: 'flex', flexDirection: 'column' }}>
        <AppBar onDownload={handleDownload} />
        <Box sx={{ flex: 1, display: 'flex', overflow: 'hidden', p: 2, gap: 2 }}>
          <Paper
            elevation={2}
            sx={{
              flex: 1,
              display: 'flex',
              flexDirection: 'column',
              overflow: 'hidden',
              p: 2,
            }}
          >
            <ProofEditor content={content} onChange={setContent} />
          </Paper>
          <Paper
            elevation={2}
            sx={{
              flex: 1,
              display: 'flex',
              flexDirection: 'column',
              overflow: 'hidden',
            }}
          >
            <ResultsPanel result={verificationResult} isVerifying={isVerifying} />
          </Paper>
        </Box>
      </Box>
    </ThemeProvider>
  );
}

export default App;
