// ============================================================================
// public/screens/agents.jsx — Agent library (list + create modal)
// ----------------------------------------------------------------------------
// Cards-on-grid layout matching the mockup. Each card shows avatar gradient,
// name, role, language, LLM, status badge, and total calls.
// Phase 4 will add the full agent editor (prompt, voice, flow); for now we
// support: list, create with basic fields, activate/archive, delete.
// ============================================================================

function AgentsScreen({ go }) {
  const [agents, setAgents]   = React.useState(null);
  const [error, setError]     = React.useState(null);
  const [showCreate, setShow] = React.useState(false);

  const load = React.useCallback(() => {
    setError(null);
    VoaisAPI.get("/api/agents").then((r) => {
      if (r.ok && r.data?.ok) setAgents(r.data.agents);
      else                    setError(r.data?.msg || "Failed to load agents.");
    });
  }, []);
  React.useEffect(load, [load]);

  const handleStatus = async (id, status) => {
    await VoaisAPI.patch("/api/agents/" + id, { status });
    load();
  };
  const handleDelete = async (id) => {
    if (!confirm("Delete this agent? This cannot be undone.")) return;
    const r = await VoaisAPI.del("/api/agents/" + id);
    if (!r.ok) { alert(r.data?.msg || "Delete failed."); return; }
    load();
  };

  if (agents === null && !error) return <DashboardSkeleton/>;

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: "var(--gap-grid)" }}>

      {/* Header */}
      <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
        <Badge tone="blue" dot>{agents?.length || 0} agents</Badge>
        <div style={{ flex: 1 }}/>
        <Btn kind="primary" size="sm" icon={<I.plus size={13}/>} onClick={() => setShow(true)}>New agent</Btn>
      </div>

      {error && (
        <div className="auth-banner err"><I.alert size={14}/><span>{error}</span></div>
      )}

      {/* Empty state */}
      {agents?.length === 0 && !error && (
        <Card>
          <div style={{ padding: "40px 24px", textAlign: "center", maxWidth: 520, margin: "0 auto" }}>
            <div style={{ width: 64, height: 64, borderRadius: 16, margin: "0 auto 20px", display: "grid", placeItems: "center", background: "var(--accent-soft)", color: "var(--accent)" }}>
              <I.agents size={28}/>
            </div>
            <h2 style={{ fontSize: 22, fontWeight: 600, letterSpacing: "-0.02em", margin: "14px 0 10px" }}>No agents yet</h2>
            <p style={{ color: "var(--ink-3)", fontSize: 13.5, lineHeight: 1.6, margin: "0 0 20px" }}>
              Agents are the AI personas that handle your calls. Create your first one — give it a name, a role, and a voice — and you'll be ready to launch campaigns.
            </p>
            <Btn kind="primary" icon={<I.plus size={14}/>} onClick={() => setShow(true)}>Create your first agent</Btn>
          </div>
        </Card>
      )}

      {/* Grid */}
      {agents && agents.length > 0 && (
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(280px, 1fr))", gap: "var(--gap-grid)" }}>
          {agents.map((a) => (
            <AgentCard key={a.id} agent={a} onStatusChange={handleStatus} onDelete={handleDelete} onEdit={(id) => go("agent_edit:" + id)}/>
          ))}
        </div>
      )}

      {showCreate && <CreateAgentModal onClose={() => setShow(false)} onCreated={() => { setShow(false); load(); }}/>}
    </div>
  );
}

// ── Agent card ──────────────────────────────────────────────────────────
function AgentCard({ agent, onStatusChange, onDelete, onEdit }) {
  const grad = agent.avatar_gradient || "linear-gradient(135deg,#5B8FFF,#00D49F)";
  const statusTone = agent.status === "active" ? "green" : agent.status === "draft" ? "gray" : "yellow";
  return (
    <Card padded={false}>
      {/* Coloured header — click to edit */}
      <div style={{ background: grad, height: 90, position: "relative", borderTopLeftRadius: "var(--r-lg)", borderTopRightRadius: "var(--r-lg)", cursor: "pointer" }}
           onClick={() => onEdit && onEdit(agent.id)}>
        <div style={{ position: "absolute", bottom: -22, left: 16 }}>
          <div style={{ width: 56, height: 56, borderRadius: 14, background: "var(--surface)", border: "3px solid var(--bg)", display: "grid", placeItems: "center", fontWeight: 700, fontSize: 22, color: "var(--accent)" }}>
            {(agent.name || "?").charAt(0).toUpperCase()}
          </div>
        </div>
        <div style={{ position: "absolute", top: 12, right: 12 }}>
          <Badge tone={statusTone} dot>{agent.status}</Badge>
        </div>
      </div>

      <div style={{ padding: "30px 16px 16px" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 6, cursor: "pointer" }}
             onClick={() => onEdit && onEdit(agent.id)}>
          <h3 style={{ margin: 0, fontSize: 16, fontWeight: 600 }}>{agent.name}</h3>
          <span style={{ fontSize: 11, color: "var(--ink-3)" }}>· {agent.code}</span>
          <I.edit size={12} style={{ color: "var(--ink-3)", marginLeft: 4 }}/>
        </div>
        <div style={{ fontSize: 12.5, color: "var(--ink-3)", marginTop: 4, lineHeight: 1.5 }}>{agent.role || "—"}</div>

        <div style={{ marginTop: 14, display: "flex", flexWrap: "wrap", gap: 6 }}>
          <Badge tone="blue">{agent.language || "—"}</Badge>
          <Badge tone="gray">{agent.llm_provider} · {agent.llm_model}</Badge>
        </div>

        <div style={{ marginTop: 14, padding: "10px 12px", background: "var(--surface-2)", borderRadius: 10, display: "flex", justifyContent: "space-between" }}>
          <div>
            <div style={{ fontSize: 11, color: "var(--ink-3)" }}>Calls handled</div>
            <div style={{ fontSize: 15, fontWeight: 600 }} className="tabular">{Number(agent.total_calls || 0).toLocaleString("en-IN")}</div>
          </div>
          <div style={{ textAlign: "right" }}>
            <div style={{ fontSize: 11, color: "var(--ink-3)" }}>Success rate</div>
            <div style={{ fontSize: 15, fontWeight: 600, color: "var(--ok)" }} className="tabular">{agent.success_rate ? `${Number(agent.success_rate)}%` : "—"}</div>
          </div>
        </div>

        <div style={{ marginTop: 14, display: "flex", gap: 8 }}>
          {agent.status === "draft" && (
            <Btn kind="primary" size="sm" style={{ flex: 1 }} onClick={() => onStatusChange(agent.id, "active")}>Activate</Btn>
          )}
          {agent.status === "active" && (
            <Btn kind="ghost" size="sm" style={{ flex: 1 }} onClick={() => onStatusChange(agent.id, "archived")}>Archive</Btn>
          )}
          {agent.status === "archived" && (
            <Btn kind="ghost" size="sm" style={{ flex: 1 }} onClick={() => onStatusChange(agent.id, "active")}>Restore</Btn>
          )}
          <Btn kind="ghost" size="sm" onClick={() => onDelete(agent.id)} title="Delete"><I.trash size={13}/></Btn>
        </div>
      </div>
    </Card>
  );
}

// ── Create agent modal ──────────────────────────────────────────────────
function CreateAgentModal({ onClose, onCreated }) {
  const [form, setForm] = React.useState({
    name: "",
    role: "",
    description: "",
    language: "hinglish",
    llm_provider: "gemini",
    llm_model: "gemini-1.5-pro",
    system_prompt: "",
    opening_script: "",
  });
  const [submitting, setSubmitting] = React.useState(false);
  const [err, setErr] = React.useState(null);

  const submit = async (e) => {
    e.preventDefault();
    setErr(null);
    if (!form.name.trim()) return setErr("Name is required.");
    setSubmitting(true);
    const r = await VoaisAPI.post("/api/agents", form);
    setSubmitting(false);
    if (r.ok) onCreated();
    else      setErr(r.data?.msg || "Failed to create agent.");
  };

  return (
    <Modal title="New AI Agent" onClose={onClose} width={580}>
      <form onSubmit={submit} style={{ display: "flex", flexDirection: "column", gap: 14 }}>
        {err && <div className="auth-banner err"><I.alert size={14}/><span>{err}</span></div>}

        <Field label="Name *">
          <input className="input" autoFocus placeholder="e.g. Priya" value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })}/>
        </Field>
        <Field label="Role" hint="What this agent does (shown on the card)">
          <input className="input" placeholder="e.g. Lead Qualification Specialist" value={form.role} onChange={(e) => setForm({ ...form, role: e.target.value })}/>
        </Field>
        <Field label="Description">
          <textarea className="textarea" rows={2} placeholder="Friendly tone, focused on demo bookings…" value={form.description} onChange={(e) => setForm({ ...form, description: e.target.value })}/>
        </Field>

        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
          <Field label="Language">
            <select className="select" value={form.language} onChange={(e) => setForm({ ...form, language: e.target.value })}>
              <option value="hinglish">Hinglish</option>
              <option value="hindi">Hindi</option>
              <option value="english">English</option>
            </select>
          </Field>
          <Field label="LLM provider">
            <select className="select" value={form.llm_provider} onChange={(e) => setForm({ ...form, llm_provider: e.target.value })}>
              <option value="gemini">Gemini</option>
              <option value="openai">OpenAI</option>
              <option value="anthropic">Anthropic</option>
            </select>
          </Field>
        </div>

        <Field label="System prompt" hint="The base instructions your agent follows on every call.">
          <textarea className="textarea" rows={3} placeholder="You are Priya, a friendly sales agent for Mercedes-Benz Lucknow…" value={form.system_prompt} onChange={(e) => setForm({ ...form, system_prompt: e.target.value })}/>
        </Field>

        <Field label="Opening script" hint="The first sentence your agent says when the call connects.">
          <textarea className="textarea" rows={2} placeholder="Namaste! Main Priya bol rahi hoon Mercedes-Benz Lucknow se…" value={form.opening_script} onChange={(e) => setForm({ ...form, opening_script: e.target.value })}/>
        </Field>

        <div style={{ display: "flex", gap: 8, justifyContent: "flex-end", marginTop: 6 }}>
          <Btn kind="ghost"   onClick={onClose} type="button">Cancel</Btn>
          <Btn kind="primary" type="submit" disabled={submitting}>
            {submitting ? "Creating…" : "Create agent"}
          </Btn>
        </div>
      </form>
    </Modal>
  );
}

window.AgentsScreen = AgentsScreen;
