import React, { useState, useEffect, useRef } from 'react';
import katex from 'katex';
import 'katex/dist/katex.min.css';

const MathInput: React.FC = () => {
  const [latex, setLatex] = useState<string>('f(x) = \\frac{1}{1+e^{-x}}');
  const inputRef = useRef<HTMLDivElement>(null);
  const [isEditing, setIsEditing] = useState<boolean>(false);

  useEffect(() => {
    renderLatex();
  }, [latex, isEditing]);

  const renderLatex = () => {
    if (inputRef.current && !isEditing) {
      try {
        katex.render(latex, inputRef.current, {
          throwOnError: false,
          displayMode: true,
        });
      } catch (error) {
        console.error('KaTeX rendering error:', error);
        inputRef.current.textContent = 'Error rendering LaTeX';
      }
    }
  };

  const handleInput = () => {
    if (inputRef.current) {
      setLatex(inputRef.current.textContent || '');
    }
  };

  const handleFocus = () => {
    setIsEditing(true);
    if (inputRef.current) {
      inputRef.current.textContent = latex;
    }
  };

  const handleBlur = () => {
    setIsEditing(false);
  };

  return (
    <div style={{ padding: '20px' }}>
      <div
        ref={inputRef}
        contentEditable
        onInput={handleInput}
        onFocus={handleFocus}
        onBlur={handleBlur}
        style={{
          width: '100%',
          padding: '10px',
          fontSize: '16px',
          border: '1px solid #ccc',
          borderRadius: '4px',
          minHeight: '40px',
          fontFamily: isEditing ? 'monospace' : 'inherit',
          cursor: 'text',
        }}
      />
    </div>
  );
};

export default MathInput;
