import { Box } from '@mui/material';
import Editor, { type OnMount } from '@monaco-editor/react';

interface ProofEditorProps {
  content: string;
  onChange: (content: string) => void;
}

const ProofEditor: React.FC<ProofEditorProps> = ({ content, onChange }) => {
  const handleEditorChange = (value: string | undefined) => {
    onChange(value || '');
  };

  const handleEditorDidMount: OnMount = (_editor, monaco) => {
    // Register the proofery language
    monaco.languages.register({ id: 'proofery' });

    // Define syntax highlighting
    monaco.languages.setMonarchTokensProvider('proofery', {
      keywords: [
        'axiom',
        'theorem',
        'suppose',
        'conclude',
        'proof',
        'exact',
        'unpack-and',
        'cases',
        'witness',
        'calculate',
        'consider',
        'forall-apply',
        'deconstruct-exists',
        'we-have',
        'focus-or',
        'define',
        'assert',
        'assert-goal',
        'goal',
      ],

      operators: ['=', '==', ':'],

      tokenizer: {
        root: [
          // Keywords
          [
            /\b(axiom|theorem|suppose|conclude|proof|exact|unpack-and|cases|witness|calculate|consider|forall-apply|deconstruct-exists|we-have|focus-or|define|assert|assert-goal|goal)\b/,
            'keyword',
          ],

          // Types (capitalized words)
          [/\b[A-Z][a-zA-Z0-9_]*\b/, 'type'],

          // Operators
          [/[=:]/, 'operator'],

          // Identifiers
          [/[a-z_][a-zA-Z0-9_]*/, 'identifier'],

          // Whitespace
          [/[ \t\r\n]+/, 'white'],
        ],
      },
    });

    // Define theme colors
    monaco.editor.defineTheme('proofery-theme', {
      base: 'vs',
      inherit: true,
      rules: [
        { token: 'keyword', foreground: '0000FF', fontStyle: 'bold' },
        { token: 'type', foreground: '267F99' },
        { token: 'operator', foreground: '000000' },
        { token: 'identifier', foreground: '000000' },
      ],
      colors: {
        'editor.foreground': '#000000',
      },
    });

    // Apply the theme
    monaco.editor.setTheme('proofery-theme');
  };

  return (
    <Box sx={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
      <Editor
        height="100%"
        defaultLanguage="proofery"
        value={content}
        onChange={handleEditorChange}
        onMount={handleEditorDidMount}
        options={{
          minimap: { enabled: false },
          fontSize: 14,
          lineNumbers: 'on',
          scrollBeyondLastLine: false,
          wordWrap: 'on',
          automaticLayout: true,
          tabSize: 4,
          insertSpaces: true,
        }}
      />
    </Box>
  );
};

export default ProofEditor;
