import { ChangeEvent, useState } from 'react';
import { transcribeAudio } from '../api';
import type { TranscriptionResult } from '../types';

export function TranscribeTab() {
  const [result, setResult] = useState<TranscriptionResult | null>(null);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);

  async function onFile(event: ChangeEvent<HTMLInputElement>) {
    const file = event.target.files?.[0];
    if (!file) return;
    setBusy(true);
    setError(null);
    setResult(null);
    try {
      setResult(await transcribeAudio(file));
    } catch (err) {
      setError(err instanceof Error ? err.message : String(err));
    } finally {
      setBusy(false);
    }
  }

  return (
    <div className="tab-body">
      <label className="upload">
        <input type="file" accept="audio/*" onChange={onFile} disabled={busy} data-testid="transcribe-file" />
        <span>{busy ? 'Transcribing…' : 'Choose an audio file'}</span>
      </label>

      {error ? <p className="error">{error}</p> : null}

      {result ? (
        <article className="message message-assistant" data-testid="transcribe-result">
          <span className="who">Transcript</span>
          <p className="body">{result.text}</p>
        </article>
      ) : null}
    </div>
  );
}
