// ============================================================================
// public/features/incoming/incoming.jsx — Incoming Calls
// ----------------------------------------------------------------------------
// A tenant can have several SIMs. Each SIM can be pointed at an AI agent so
// that when someone calls that SIM's number, the agent answers, talks, and the
// call flows through the same pipeline as an outbound AI call (transcript,
// recording, analysis, auto end-call). Routing is per-SIM: sims.inbound_agent_id.
// The one external step is a single Asterisk dialplan line on the tenant's box,
// documented in the "Connect your Asterisk" card below.
// ============================================================================

function IncomingScreen() {
  const [sims, setSims]     = React.useState(null);
  const [agents, setAgents] = React.useState([]);
  const [ariApp, setAriApp] = React.useState("voicegsm");
  const [savingId, setSaving] = React.useState(null);
  const [savedId, setSaved]   = React.useState(null);
  const [copied, setCopied]   = React.useState(false);

  const load = React.useCallback(() => {
    VoaisAPI.get("/api/settings/sims").then(r => { if (r.ok && r.data?.ok) setSims(r.data.sims || []); });
    VoaisAPI.get("/api/agents").then(r => { if (r.ok && r.data?.ok) setAgents(r.data.agents || []); });
    VoaisAPI.get("/api/settings/telephony").then(r => {
      if (r.ok && r.data?.ok && r.data.config?.ari_app) setAriApp(r.data.config.ari_app);
    });
  }, []);
  React.useEffect(() => { load(); }, [load]);

  const assign = async (sim, agentId) => {
    const val = agentId ? Number(agentId) : null;
    setSaving(sim.id);
    const r = await VoaisAPI.patch(`/api/settings/sims/${sim.id}`, { inbound_agent_id: val });
    setSaving(null);
    if (r.ok && r.data?.ok) {
      setSims(prev => prev.map(s => s.id === sim.id
        ? { ...s, inbound_agent_id: val, inbound_agent_name: (agents.find(a => a.id === val) || {}).name || null }
        : s));
      setSaved(sim.id); setTimeout(() => setSaved(null), 1500);
    }
  };

  if (!sims) return <DashboardSkeleton/>;

  const answering = sims.filter(s => s.inbound_agent_id);
  const dialplan =
`; Ships in your VoAIs Asterisk setup (deploy/asterisk/extensions.conf).
; The Dinstar trunk already lands inbound calls in this context.
[from-dinstar]
exten => _X.,1,NoOp(Incoming GSM from \${CALLERID(num)} to \${EXTEN})
 same => n,Answer()
 same => n,Stasis(${ariApp},inbound,\${EXTEN},\${CALLERID(num)})
 same => n,Hangup()`;

  const copyDialplan = () => {
    try { navigator.clipboard.writeText(dialplan); setCopied(true); setTimeout(() => setCopied(false), 1500); } catch (_) {}
  };

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

      {/* ── How it works ─────────────────────────────────────────── */}
      <Card>
        <CardHead
          icon={<I.phoneIn/>}
          title="How incoming calls work"
          subtitle="Assign an AI agent to a SIM. When someone calls that number, the agent picks up and talks — with live transcript, recording, and post-call analysis, just like an outbound call."
        />
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(210px, 1fr))", gap: 10, marginTop: 14 }}>
          <Step n="1" title="Someone calls your SIM" desc="A caller dials the mobile number of one of your GSM SIMs."/>
          <Step n="2" title="Your Asterisk hands it to us" desc="A one-line dialplan rule routes the call into the AI (see below)."/>
          <Step n="3" title="The agent answers" desc="The AI agent you assigned to that SIM greets the caller and handles the conversation."/>
        </div>
      </Card>

      {/* ── Per-SIM answer rules ─────────────────────────────────── */}
      <Card>
        <CardHead
          title="Answer rules"
          subtitle="Each SIM answers with its own agent. Pick “Don’t answer” to ignore inbound calls on that SIM."
          right={<Badge tone={answering.length ? "green" : "gray"}>{answering.length} of {sims.length} answering</Badge>}
        />

        {sims.length === 0 ? (
          <div style={{ padding: "28px 8px", textAlign: "center", color: "var(--ink-3)" }}>
            <I.phone size={30} style={{ opacity: 0.3, marginBottom: 10 }}/>
            <div style={{ fontSize: 14, fontWeight: 600, color: "var(--ink-1)" }}>No SIMs yet</div>
            <div style={{ fontSize: 13, marginTop: 4 }}>Add your GSM SIMs in <b>Settings → Telephony</b>, then assign an agent to each here.</div>
          </div>
        ) : (
          <div style={{ overflowX: "auto", marginTop: 12 }}>
            <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 13 }}>
              <thead>
                <tr style={{ textAlign: "left", color: "var(--ink-3)", fontSize: 11.5, textTransform: "uppercase", letterSpacing: 0.4 }}>
                  <th style={{ padding: "8px 10px" }}>SIM</th>
                  <th style={{ padding: "8px 10px" }}>Number</th>
                  <th style={{ padding: "8px 10px" }}>Port</th>
                  <th style={{ padding: "8px 10px", minWidth: 220 }}>Answers with</th>
                  <th style={{ padding: "8px 10px", width: 90 }}></th>
                </tr>
              </thead>
              <tbody>
                {sims.map(sim => (
                  <tr key={sim.id} style={{ borderTop: "1px solid var(--line)" }}>
                    <td style={{ padding: "10px" }}>
                      <div style={{ fontWeight: 600 }}>{sim.label || `SIM ${sim.port}`}</div>
                      {!sim.active && <Badge tone="gray">inactive</Badge>}
                    </td>
                    <td style={{ padding: "10px", color: "var(--ink-3)" }}>{sim.phone_number || "—"}</td>
                    <td style={{ padding: "10px", fontFamily: "var(--font-mono)", color: "var(--ink-3)" }}>{sim.port}</td>
                    <td style={{ padding: "10px" }}>
                      <select className="input" value={sim.inbound_agent_id || ""}
                        onChange={e => assign(sim, e.target.value)}
                        style={{ maxWidth: 260 }}>
                        <option value="">Don’t answer incoming</option>
                        {agents.map(a => <option key={a.id} value={a.id}>{a.name}</option>)}
                      </select>
                    </td>
                    <td style={{ padding: "10px" }}>
                      {savingId === sim.id ? <span style={{ fontSize: 12, color: "var(--ink-3)" }}>Saving…</span>
                        : savedId === sim.id ? <Badge tone="green">Saved</Badge>
                        : sim.inbound_agent_id ? <Badge tone="green">On</Badge>
                        : <span style={{ fontSize: 12, color: "var(--ink-3)" }}>Off</span>}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
        {agents.length === 0 && sims.length > 0 && (
          <div style={{ marginTop: 12, fontSize: 12.5, color: "var(--warn)" }}>
            You have no AI agents yet — create one in <b>AI Agents</b> first, then assign it here.
          </div>
        )}
      </Card>

      {/* ── Connect your Asterisk ────────────────────────────────── */}
      <Card>
        <CardHead
          title="Connect your gateway"
          subtitle="If you set up VoAIs with our deploy bundle, the Asterisk side is already done. You only need to enable inbound on the Dinstar."
          right={<Btn kind="ghost" size="sm" onClick={copyDialplan}>{copied ? "Copied ✓" : "Copy dialplan"}</Btn>}
        />
        <ol style={{ margin: "12px 0 0", paddingLeft: 18, fontSize: 13, color: "var(--ink-2)", lineHeight: 1.7 }}>
          <li><b>Assign an agent above</b> — that's the only step inside VoAIs.</li>
          <li>On your <b>Dinstar</b> gateway, add a <b>Mobile → IP</b> (inbound) route sending incoming GSM calls to your Asterisk. This is the mirror of the IP → Mobile route you already use for outbound.</li>
          <li><b>Asterisk needs no change</b> if you deployed with our bundle — it already routes the Dinstar into the <code>from-dinstar</code> context below. (Shown for reference / manual setups.)</li>
        </ol>
        <pre style={{
          marginTop: 10, padding: 14, background: "var(--surface-2)", borderRadius: "var(--r-md)",
          border: "1px solid var(--line)", overflowX: "auto", fontSize: 12.5, lineHeight: 1.6,
          fontFamily: "var(--font-mono)", color: "var(--ink-1)", whiteSpace: "pre",
        }}>{dialplan}</pre>
        <div style={{ marginTop: 10, fontSize: 12.5, color: "var(--ink-3)" }}>
          Your Stasis app is <code>{ariApp}</code>. With multiple SIMs, routing uses the dialed number
          (each SIM's <b>Number</b> field); with one SIM it just answers with that SIM's agent. Nothing else
          on your side changes — WireGuard and ARI are the same as outbound.
        </div>
      </Card>

    </div>
  );
}

function Step({ n, title, desc }) {
  return (
    <div style={{ padding: 14, background: "var(--surface-2)", borderRadius: "var(--r-md)", border: "1px solid var(--line)" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 6 }}>
        <span style={{
          width: 22, height: 22, borderRadius: 11, background: "var(--accent-soft)", color: "var(--accent)",
          display: "grid", placeItems: "center", fontSize: 12, fontWeight: 700,
        }}>{n}</span>
        <span style={{ fontSize: 13, fontWeight: 600 }}>{title}</span>
      </div>
      <div style={{ fontSize: 12, color: "var(--ink-3)", lineHeight: 1.5 }}>{desc}</div>
    </div>
  );
}

window.IncomingScreen = IncomingScreen;
