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

const SAMPLE_EMAIL = {
  sender_email: "Customer Example <customer@example.com>",
  subject: "Refund request for pi_test123",
  body: "Please refund 25.00 USD for payment pi_test123.",
  message_id: "<sample-support-email@example.com>",
  stripe_payment_intent_id: "pi_test123",
  requested_refund_amount_cents: 2500,
  currency: "usd",
  customer_name: "Customer",
};

export function App() {
  const [config, setConfig] = useState(null);
  const [session, setSession] = useState(null);
  const [selectedSkillName, setSelectedSkillName] = useState("process_support_email");
  const [argsText, setArgsText] = useState(JSON.stringify(SAMPLE_EMAIL, null, 2));
  const [result, setResult] = useState(null);
  const [error, setError] = useState(null);
  const [running, setRunning] = useState(false);

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

  const selectedSkill = useMemo(
    () => config?.skills?.find((skill) => skill.name === selectedSkillName),
    [config, selectedSkillName],
  );

  function selectSkill(name) {
    setSelectedSkillName(name);
    setResult(null);
    setError(null);
    if (name === "process_support_email") setArgsText(JSON.stringify(SAMPLE_EMAIL, null, 2));
    if (name === "execute_approved_refund") {
      setArgsText(JSON.stringify({
        action_digest: "paste_action_digest_from_preview",
        approval_token: "APPROVE-REFUND-first16digest",
        stripe_payment_intent_id: "pi_test123",
        amount_cents: 2500,
        currency: "usd",
        customer_email: "customer@example.com",
        reason: "requested_by_customer",
      }, null, 2));
    }
  }

  async function runSkill(event) {
    event.preventDefault();
    if (!config || !selectedSkill) return;
    setRunning(true);
    setError(null);
    setResult(null);
    try {
      const args = JSON.parse(argsText || "{}");
      const data = await callSkill(config, selectedSkill.name, args);
      setResult(data);
    } catch (err) {
      setError(err.message || String(err));
    } finally {
      setRunning(false);
    }
  }

  if (!config) {
    return <main className="loading"><p>{error || "Loading support refund agent..."}</p></main>;
  }

  const skills = config.skills || [];

  return (
    <main className="app-shell">
      <aside className="sidebar">
        <div>
          <p className="eyebrow">Support refund workflow</p>
          <h1>Refund approval card</h1>
          <p className="agent-meta">{config.agent.name} v{config.agent.version}</p>
        </div>

        <div className="panel compact">
          <h3>Safety model</h3>
          <p>Inbound email can only create a proposal and draft. Stripe refunds require a separate approval token bound to the action digest.</p>
        </div>

        <nav className="skill-list" aria-label="Agent skills">
          {skills.map((skill) => (
            <button className={skill.name === selectedSkillName ? "skill active" : "skill"} key={skill.name} onClick={() => selectSkill(skill.name)} type="button">
              <span>{skill.name}</span>
              <small>{skill.tags?.includes("a2a:email-handler") ? "email" : "tool"}</small>
            </button>
          ))}
        </nav>

        <div className="session">
          <span>{session?.authenticated ? "Signed in" : "Local session"}</span>
          <strong>{session?.user?.email || session?.org?.slug || "dev@example.local"}</strong>
        </div>
      </aside>

      <section className="workbench">
        <header className="toolbar">
          <div>
            <p className="eyebrow">Chat-style runner</p>
            <h2>{selectedSkill?.name || "No skills found"}</h2>
          </div>
          <a href={config.docs.base} rel="noreferrer" target="_blank">Docs</a>
        </header>

        <form className="runner" onSubmit={runSkill}>
          <label>
            Message / approval JSON
            <textarea spellCheck="false" value={argsText} onChange={(event) => setArgsText(event.target.value)} />
          </label>
          <button disabled={running || !selectedSkill} type="submit">{running ? "Running..." : "Send to agent"}</button>
        </form>

        <section className="panels">
          <div className="panel">
            <h3>Agent reply</h3>
            <pre>{error || JSON.stringify(result, null, 2) || "No run yet."}</pre>
          </div>
          <div className="panel">
            <h3>Published input schema</h3>
            <pre>{JSON.stringify(selectedSkill?.input_schema || {}, null, 2)}</pre>
          </div>
        </section>
      </section>
    </main>
  );
}
