import { useEffect, useMemo, useState } from "react";
import { callSkill, loadAgentConfig, loadSession, signInUrl } from "./a2a.js";

const DEFAULT_FORM = {
  asset_type: "character",
  theme: "forest knight",
  palette: "#22c55e, #14532d, #facc15",
  size: 128,
  style: "pixel",
  variant_count: 2,
};

export function App() {
  const [config, setConfig] = useState(null);
  const [session, setSession] = useState(null);
  const [form, setForm] = useState(DEFAULT_FORM);
  const [result, setResult] = useState(null);
  const [receipts, setReceipts] = useState([]);
  const [error, setError] = useState(null);
  const [running, setRunning] = useState(false);
  const [loadingReceipts, setLoadingReceipts] = useState(false);

  useEffect(() => {
    loadAgentConfig()
      .then((data) => {
        setConfig(data);
        return loadSession(data).catch(() => ({ authenticated: false }));
      })
      .then((sessionData) => setSession(sessionData))
      .catch((err) => setError(err.message || String(err)));
  }, []);

  const generateSkill = useMemo(
    () => config?.skills?.find((skill) => skill.name === "generate_svg_asset"),
    [config],
  );
  const listSkill = useMemo(
    () => config?.skills?.find((skill) => skill.name === "list_recent_receipts"),
    [config],
  );
  const needsSignIn = Boolean(config?.auth?.invokeRequiresSession && session && !session.authenticated);
  const signInHref = useMemo(() => (config ? signInUrl(config) : null), [config]);

  function update(field, value) {
    setForm((current) => ({ ...current, [field]: value }));
  }

  function requestPayload() {
    return {
      asset_type: form.asset_type,
      theme: form.theme.trim(),
      palette: form.palette.split(",").map((item) => item.trim()).filter(Boolean),
      size: Number(form.size),
      style: form.style,
      variant_count: Number(form.variant_count),
    };
  }

  async function generateAsset(event) {
    event.preventDefault();
    if (!config || !generateSkill) return;
    setRunning(true);
    setError(null);
    setResult(null);
    try {
      const data = await callSkill(config, "generate_svg_asset", requestPayload());
      setResult(data);
      if (data?.status === "setup_required") {
        setError(data.warning || "Setup is required before this skill can run.");
      }
      if (listSkill) loadReceipts();
    } catch (err) {
      setError(err.message || String(err));
    } finally {
      setRunning(false);
    }
  }

  async function loadReceipts() {
    if (!config || !listSkill) return;
    setLoadingReceipts(true);
    try {
      const data = await callSkill(config, "list_recent_receipts", { limit: 8 });
      if (data.status === "ok") setReceipts(data.receipts || []);
    } catch (err) {
      if (!String(err.message || err).toLowerCase().includes("sign in")) {
        setError(err.message || String(err));
      }
    } finally {
      setLoadingReceipts(false);
    }
  }

  if (!config) {
    return <main className="loading"><p>{error || "Loading SVG asset studio..."}</p></main>;
  }

  return (
    <main className="app-shell">
      <section className="hero">
        <div>
          <p className="eyebrow">SVG game asset generator</p>
          <h1>Generate production-ready SVG sprites for your game.</h1>
          <p className="lede">
            Choose an asset type, style, size, and palette. The backend returns inline SVG assets
            and persists a signed-in execution receipt when deployed with managed Postgres.
          </p>
        </div>
        <div className="session-card">
          <span>{session?.authenticated ? "Signed in" : "Sign-in required to run"}</span>
          <strong>{session?.user?.email || session?.email || config.agent?.name}</strong>
          {needsSignIn && signInHref ? <a href={signInHref}>Sign in with A2A Cloud</a> : null}
        </div>
      </section>

      <section className="workspace">
        <form className="generator-card" onSubmit={generateAsset}>
          <div className="form-grid">
            <label>
              Asset type
              <select value={form.asset_type} onChange={(event) => update("asset_type", event.target.value)}>
                <option value="character">Character</option>
                <option value="enemy">Enemy</option>
                <option value="item">Item</option>
                <option value="tile">Tile</option>
                <option value="icon">Icon</option>
                <option value="projectile">Projectile</option>
              </select>
            </label>
            <label>
              Style
              <select value={form.style} onChange={(event) => update("style", event.target.value)}>
                <option value="pixel">Pixel</option>
                <option value="flat">Flat</option>
                <option value="outline">Outline</option>
                <option value="neon">Neon</option>
              </select>
            </label>
            <label className="wide">
              Theme prompt
              <input maxLength={80} minLength={2} value={form.theme} onChange={(event) => update("theme", event.target.value)} />
            </label>
            <label className="wide">
              Palette (#RRGGBB, comma-separated, max 5)
              <input value={form.palette} onChange={(event) => update("palette", event.target.value)} />
            </label>
            <label>
              Canvas size
              <input max={512} min={32} type="number" value={form.size} onChange={(event) => update("size", event.target.value)} />
            </label>
            <label>
              Variants
              <input max={4} min={1} type="number" value={form.variant_count} onChange={(event) => update("variant_count", event.target.value)} />
            </label>
          </div>
          <button disabled={running || needsSignIn} type="submit">
            {running ? "Generating..." : "Generate SVG assets"}
          </button>
          {needsSignIn ? <p className="hint">Sign in to invoke backend tools and persist receipts.</p> : null}
          {error ? <p className="error">{error}</p> : null}
        </form>

        <aside className="receipt-card">
          <div className="receipt-header">
            <div>
              <p className="eyebrow">Receipts</p>
              <h2>Recent runs</h2>
            </div>
            <button disabled={loadingReceipts || needsSignIn} onClick={loadReceipts} type="button">
              {loadingReceipts ? "Loading..." : "Refresh"}
            </button>
          </div>
          {receipts.length ? (
            <ul className="receipts">
              {receipts.map((item) => (
                <li key={item.receipt_id}>
                  <strong>{item.theme}</strong>
                  <span>{item.asset_type} · {item.style} · {item.variant_count} variant(s)</span>
                  <code>{item.receipt_id}</code>
                </li>
              ))}
            </ul>
          ) : (
            <p className="empty">No persisted receipts loaded yet.</p>
          )}
        </aside>
      </section>

      <section className="results">
        <div className="result-header">
          <div>
            <p className="eyebrow">Generated assets</p>
            <h2>{result?.status === "ok" ? `${result.svg_assets?.length || 0} SVG asset(s)` : "Preview"}</h2>
          </div>
          {result?.receipt_id ? <code>{result.receipt_id}</code> : null}
        </div>
        {result?.warnings?.length ? <p className="warning">{result.warnings.join(" · ")}</p> : null}
        <div className="asset-grid">
          {(result?.svg_assets || []).map((asset) => (
            <article className="asset" key={asset.name}>
              <div className="svg-preview" dangerouslySetInnerHTML={{ __html: asset.svg }} />
              <div className="asset-meta">
                <strong>{asset.name}</strong>
                <button type="button" onClick={() => navigator.clipboard?.writeText(asset.svg)}>Copy SVG</button>
              </div>
            </article>
          ))}
          {!result ? <p className="empty">Submit the form to render SVG assets from the live backend.</p> : null}
        </div>
      </section>
    </main>
  );
}
