import { FormEvent, useState } from 'react';
import { synthesizeSpeech } from '../api';

export function SpeechTab() {
  const [text, setText] = useState('Hello from Kazzle.');
  const [audioUrl, setAudioUrl] = useState<string | null>(null);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);

  async function onSubmit(event: FormEvent) {
    event.preventDefault();
    if (!text.trim() || busy) return;
    setBusy(true);
    setError(null);
    try {
      const blob = await synthesizeSpeech(text);
      // Revoke the previous URL to avoid leaking blob handles across
      // multiple syntheses in the same session.
      if (audioUrl) URL.revokeObjectURL(audioUrl);
      setAudioUrl(URL.createObjectURL(blob));
    } catch (err) {
      setError(err instanceof Error ? err.message : String(err));
    } finally {
      setBusy(false);
    }
  }

  return (
    <div className="tab-body">
      <form className="composer" onSubmit={onSubmit}>
        <input
          value={text}
          onChange={e => setText(e.target.value)}
          placeholder="Text to speak…"
          disabled={busy}
          data-testid="speech-text"
        />
        <button type="submit" disabled={busy || !text.trim()} data-testid="speech-go">
          {busy ? 'Synthesising…' : 'Speak'}
        </button>
      </form>

      {error ? <p className="error">{error}</p> : null}
      {audioUrl ? <audio src={audioUrl} controls data-testid="speech-audio" /> : null}
    </div>
  );
}
