import { FormEvent, useState } from 'react';
import { generateImage } from '../api';
import type { ImageResult } from '../types';

export function ImageTab() {
  const [prompt, setPrompt] = useState('a single red dot on white');
  const [result, setResult] = useState<ImageResult | null>(null);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);

  async function onSubmit(event: FormEvent) {
    event.preventDefault();
    if (!prompt.trim() || busy) return;
    setBusy(true);
    setError(null);
    setResult(null);
    try {
      setResult(await generateImage(prompt));
    } 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={prompt}
          onChange={e => setPrompt(e.target.value)}
          placeholder="Describe an image…"
          disabled={busy}
          data-testid="image-prompt"
        />
        <button type="submit" disabled={busy || !prompt.trim()} data-testid="image-go">
          {busy ? 'Generating…' : 'Generate'}
        </button>
      </form>

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

      <div className="image-grid" data-testid="image-result">
        {result?.images.map((img, idx) => {
          const src = img.b64 ? `data:${img.mimeType};base64,${img.b64}` : img.url;
          return src ? <img key={idx} src={src} alt="" /> : null;
        })}
      </div>
    </div>
  );
}
