import Editor from '@monaco-editor/react';
import { useKV } from '@github/spark/hooks';
import { useEffect } from 'react';

interface CodeEditorProps {
  onCodeChange?: (code: string) => void;
}

export function CodeEditor({ onCodeChange }: CodeEditorProps) {
  const [code, setCode] = useKV('aethex-current-code', `-- Welcome to AeThex Studio!
-- Write your Roblox Lua code here

local Players = game:GetService("Players")

Players.PlayerAdded:Connect(function(player)
    print(player.Name .. " joined the game!")
    
    local leaderstats = Instance.new("Folder")
    leaderstats.Name = "leaderstats"
    leaderstats.Parent = player
    
    local coins = Instance.new("IntValue")
    coins.Name = "Coins"
    coins.Value = 0
    coins.Parent = leaderstats
end)
`);

  useEffect(() => {
    if (onCodeChange && code) {
      onCodeChange(code);
    }
  }, [code, onCodeChange]);

  const handleEditorChange = (value: string | undefined) => {
    setCode(value || '');
  };

  return (
    <div className="h-full w-full">
      <Editor
        height="100%"
        defaultLanguage="lua"
        theme="vs-dark"
        value={code}
        onChange={handleEditorChange}
        options={{
          minimap: { enabled: window.innerWidth >= 768 },
          fontSize: 14,
          lineNumbers: 'on',
          automaticLayout: true,
          scrollBeyondLastLine: false,
          wordWrap: 'on',
          fontFamily: 'JetBrains Mono, monospace',
          fontLigatures: true,
          cursorBlinking: 'smooth',
          smoothScrolling: true,
          padding: { top: 16, bottom: 16 },
        }}
      />
    </div>
  );
}
