'use client';

import { useState } from 'react';
import { runCode } from '@/actions';  // 导入 Server Action

const CodeRunner = () => {
  const [code, setCode] = useState('');
  const [language, setLanguage] = useState('c');
  const [output, setOutput] = useState('');
  const [error, setError] = useState('');

  const runCodeHandler = async () => {
    try {
      // 调用 Server Action 执行代码
      const result = await runCode({ code, language });

      setOutput(result.output);
      setError('');
    } catch (err) {
      setError((err as Error).message);
      setOutput('');
    }
  };

  return (
      <div>
        <h1>Code Runner</h1>
        <textarea
            value={code}
            onChange={(e) => setCode(e.target.value)}
            placeholder="Write your code here"
            rows={10}
            cols={50}
        />
        <div>
          <label>
            Language:
            <select value={language} onChange={(e) => setLanguage(e.target.value)}>
              <option value="c">C</option>
              <option value="java">Java</option>
            </select>
          </label>
        </div>
        <button onClick={runCodeHandler}>Run Code</button>

        {output && (
            <div>
              <h3>Output:</h3>
              <pre>{output}</pre>
            </div>
        )}
        {error && (
            <div>
              <h3>Error:</h3>
              <pre>{error}</pre>
            </div>
        )}
      </div>
  );
};

export default CodeRunner;
