import React, { useState, useEffect, useRef } from 'react';

const CodeEditor = ({ code, onCodeChange, language = 'javascript' }) => {
  const textareaRef = useRef(null);
  const [cursorPosition, setCursorPosition] = useState(0);
  const [suggestions, setSuggestions] = useState([]);
  const [showSuggestions, setShowSuggestions] = useState(false);

  useEffect(() => {
    if (textareaRef.current) {
      textareaRef.current.focus();
    }
  }, []);

  const handleKeyDown = (e) => {
    if (e.key === 'Tab') {
      e.preventDefault();
      const start = e.target.selectionStart;
      const end = e.target.selectionEnd;
      const newValue = code.substring(0, start) + '  ' + code.substring(end);
      onCodeChange(newValue);
      setCursorPosition(start + 2);
    }
  };

  const handleInputChange = (e) => {
    const newCode = e.target.value;
    onCodeChange(newCode);
    
    // Simple suggestion logic
    if (newCode.includes('function') || newCode.includes('const') || newCode.includes('let')) {
      setSuggestions([
        'console.log("Hello World")',
        'return',
        'async function',
        'await',
        'try {',
        'catch (error) {'
      ]);
      setShowSuggestions(true);
    } else {
      setShowSuggestions(false);
    }
  };

  return (
    <div className="relative w-full">
      <textarea
        ref={textareaRef}
        value={code}
        onChange={handleInputChange}
        onKeyDown={handleKeyDown}
        className="w-full h-96 p-4 bg-gray-900 text-green-400 font-mono text-sm rounded-lg border border-gray-700 focus:outline-none focus:border-blue-500 resize-none"
        placeholder="// Start coding here..."
      />
      {showSuggestions && (
        <div className="absolute top-full left-0 mt-2 w-full bg-gray-800 border border-gray-700 rounded-lg shadow-lg z-10">
          {suggestions.map((suggestion, index) => (
            <div
              key={index}
              className="px-4 py-2 hover:bg-gray-700 cursor-pointer text-gray-300 text-sm"
              onClick={() => {
                const newCode = code + '\n' + suggestion;
                onCodeChange(newCode);
                setShowSuggestions(false);

            >
              {suggestion}
            </div>
          ))}
        </div>
      )}
    </div>
  );
};

export default CodeEditor;