// ============================================================================
// public/screens/settings.jsx — Tenant Settings (SaaS-aware)
// ----------------------------------------------------------------------------
// Tenants configure their OWN telephony infrastructure (Asterisk, GSM, SIMs).
// They do NOT see AI provider keys — those are platform-managed (Hidrogen IP).
//
// Tabs: Profile | Telephony | SIM Cards | Advanced
// ============================================================================

function SettingsScreen({ session }) {
  const [tab, setTab] = React.useState("telephony");

  const tabs = [
    { id: "profile",    label: "Profile" },
    { id: "telephony",  label: "Telephony" },
    { id: "sims",       label: "SIM Cards" },
    { id: "advanced",   label: "Advanced" },
  ];

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: "var(--gap-grid)" }}>
      <div style={{ display: "flex", gap: 4, background: "var(--surface)", border: "1px solid var(--line)", borderRadius: 12, padding: 4, width: "fit-content" }}>
        {tabs.map((t) => (
          <button
            key={t.id}
            className={`btn ${tab === t.id ? "btn-primary" : "btn-ghost"}`}
            style={{ borderRadius: 8, padding: "8px 16px", fontSize: 13 }}
            onClick={() => setTab(t.id)}
          >
            {t.label}
          </button>
        ))}
      </div>

      {tab === "profile"   && <ProfileTab session={session}/>}
      {tab === "telephony" && <TelephonyTab/>}
      {tab === "sims"      && <SimsTab/>}
      {tab === "advanced"  && <AdvancedTab/>}
    </div>
  );
}

// ── Profile tab ─────────────────────────────────────────────────────────
function ProfileTab({ session }) {
  const [form, setForm] = React.useState({
    name: session?.user?.name || "",
    phone: session?.user?.phone || "",
    title: session?.user?.title || "",
  });
  const [saving, setSaving] = React.useState(false);
  const [msg, setMsg] = React.useState(null);

  const save = async () => {
    setSaving(true); setMsg(null);
    const r = await VoaisAPI.patch("/api/me/profile", form);
    setSaving(false);
    setMsg(r.ok ? { type: "ok", text: "Profile updated." } : { type: "err", text: r.data?.msg || "Failed." });
  };

  return (
    <Card>
      <CardHead title="Your profile"/>
      <div style={{ display: "flex", flexDirection: "column", gap: 14, maxWidth: 480, marginTop: 10 }}>
        {msg && <div className={`auth-banner ${msg.type}`}><I.alert size={14}/><span>{msg.text}</span></div>}
        <Field label="Full name">
          <input className="input" value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })}/>
        </Field>
        <Field label="Phone">
          <input className="input" value={form.phone} onChange={(e) => setForm({ ...form, phone: e.target.value })}/>
        </Field>
        <Field label="Title / Role">
          <input className="input" placeholder="e.g. Founder & CEO" value={form.title} onChange={(e) => setForm({ ...form, title: e.target.value })}/>
        </Field>
        <Btn kind="primary" onClick={save} disabled={saving}>{saving ? "Saving…" : "Save profile"}</Btn>
      </div>
    </Card>
  );
}

// ── Telephony tab (their own Asterisk + GSM gateway) ─────────────────
function TelephonyTab() {
  const [data, setData] = React.useState(null);
  const [status, setStatus] = React.useState(null);
  const [form, setForm] = React.useState({});
  const [saving, setSaving] = React.useState(false);
  const [testing, setTesting] = React.useState(false);
  const [msg, setMsg] = React.useState(null);
  const [loading, setLoading] = React.useState(true);

  const reload = React.useCallback(() => {
    Promise.all([
      VoaisAPI.get("/api/telephony/settings"),
      VoaisAPI.get("/api/telephony/status"),
    ]).then(([s, st]) => {
      if (s.ok && s.data?.ok) {
        setData(s.data);
        setForm({ ...s.data.settings });
      }
      if (st.ok && st.data?.ok) setStatus(st.data);
      setLoading(false);
    });
  }, []);

  React.useEffect(reload, [reload]);

  const save = async () => {
    setSaving(true); setMsg(null);
    const r = await VoaisAPI.patch("/api/telephony/settings", form);
    setSaving(false);
    if (r.ok) {
      setMsg({ type: "ok", text: `${r.data?.saved || 0} settings saved. Changes are live — next call will use the new values.` });
      reload();
    } else {
      setMsg({ type: "err", text: r.data?.msg || "Save failed." });
    }
  };

  const testConnection = async () => {
    setTesting(true); setMsg(null);
    const r = await VoaisAPI.post("/api/telephony/test-connection", {});
    setTesting(false);
    if (r.ok && r.data?.ok) {
      setMsg({ type: "ok", text: "Connected to your Asterisk successfully!" });
    } else {
      setMsg({ type: "err", text: r.data?.msg || "Connection failed. Check your AMI host/credentials." });
    }
    reload();
  };

  if (loading) return <Card><div style={{ padding: 40, textAlign: "center", color: "var(--ink-3)" }}>Loading telephony settings…</div></Card>;

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

      {/* Intro card */}
      <Card>
        <div style={{ display: "flex", gap: 14, alignItems: "flex-start" }}>
          <div style={{ width: 40, height: 40, borderRadius: 10, display: "grid", placeItems: "center", background: "var(--accent-soft)", color: "var(--accent)", flexShrink: 0 }}>
            <I.phone size={18}/>
          </div>
          <div style={{ flex: 1 }}>
            <h3 style={{ margin: "0 0 6px", fontSize: 15, fontWeight: 600 }}>Bring Your Own Telephony</h3>
            <p style={{ margin: 0, fontSize: 13, color: "var(--ink-3)", lineHeight: 1.6 }}>
              VoAIs is the AI brain + CRM. <b style={{ color: "var(--ink)" }}>You bring your own Asterisk PBX and GSM gateway.</b> Configure how we should connect to your infrastructure below. Don't worry about AI keys — those are managed for you.
            </p>
          </div>
        </div>
      </Card>

      {/* Status strip */}
      {status && (
        <Card>
          <div style={{ display: "flex", flexWrap: "wrap", gap: 24, alignItems: "center" }}>
            <StatusDot label="AMI Configured" on={status.ami?.configured}/>
            <StatusDot label="AMI Connected" on={status.ami?.connected}/>
            <StatusDot label="ARI Configured" on={status.ari?.configured}/>
            <StatusDot label="AI Brain (Hidrogen)" on={status.ai?.enabled}/>
            <div style={{ flex: 1 }}/>
            {status.ready ? (
              <Badge tone="green" dot>Ready to dial</Badge>
            ) : (
              <Badge tone="yellow" dot>Setup incomplete</Badge>
            )}
          </div>
          {status.ai?.providers?.length > 0 && (
            <div style={{ marginTop: 10, fontSize: 12, color: "var(--ink-3)" }}>
              AI providers available: <b style={{ color: "var(--ink)" }}>{status.ai.providers.join(", ")}</b> · Default model: <b style={{ color: "var(--ink)" }}>{status.ai.defaultModel}</b>
            </div>
          )}
        </Card>
      )}

      {msg && (
        <div className={`auth-banner ${msg.type}`} style={{ marginBottom: 0 }}>
          <I.alert size={14}/><span>{msg.text}</span>
        </div>
      )}

      {/* Settings groups (all tenant-level — no AI keys exposed) */}
      {(data?.groups || []).map((group) => (
        <SettingsGroup
          key={group.id}
          group={group}
          form={form}
          onChange={(k, v) => setForm({ ...form, [k]: v })}
          secretSnapshot={data?.settings || {}}
        />
      ))}

      {/* Sticky action bar */}
      <div style={{ display: "flex", gap: 10, position: "sticky", bottom: 16, zIndex: 5, background: "var(--bg)", padding: "12px 0" }}>
        <Btn kind="primary" onClick={save} disabled={saving} icon={<I.check size={14}/>}>
          {saving ? "Saving…" : "Save telephony settings"}
        </Btn>
        <Btn kind="ghost" onClick={testConnection} disabled={testing} icon={<I.zap size={14}/>}>
          {testing ? "Testing…" : "Test connection"}
        </Btn>
        <Btn kind="ghost" onClick={() => setForm({ ...data?.settings || {} })}>Reset</Btn>
      </div>
    </div>
  );
}

// ── SIM Cards tab ───────────────────────────────────────────────────────
function SimsTab() {
  const [sims, setSims] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [showAdd, setShowAdd] = React.useState(false);

  const load = () => {
    setLoading(true);
    VoaisAPI.get("/api/telephony/sims").then((r) => {
      if (r.ok && r.data?.ok) setSims(r.data.sims || []);
      setLoading(false);
    });
  };
  React.useEffect(load, []);

  const toggleActive = async (sim) => {
    await VoaisAPI.patch("/api/telephony/sims/" + sim.id, { active: sim.active ? 0 : 1 });
    load();
  };
  const deleteSim = async (sim) => {
    if (!confirm("Delete SIM port " + sim.port + "?")) return;
    await VoaisAPI.del("/api/telephony/sims/" + sim.id);
    load();
  };

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: "var(--gap-grid)" }}>
      <Card>
        <div style={{ display: "flex", gap: 14, alignItems: "flex-start" }}>
          <div style={{ width: 40, height: 40, borderRadius: 10, display: "grid", placeItems: "center", background: "var(--accent-soft)", color: "var(--accent)", flexShrink: 0 }}>
            <I.template size={18}/>
          </div>
          <div style={{ flex: 1 }}>
            <h3 style={{ margin: "0 0 6px", fontSize: 15, fontWeight: 600 }}>Your SIM Cards</h3>
            <p style={{ margin: 0, fontSize: 13, color: "var(--ink-3)", lineHeight: 1.6 }}>
              The SIM cards in your GSM gateway. Each port maps to a phone line we'll route calls through. Active SIMs are used round-robin across all your campaigns.
            </p>
          </div>
        </div>
      </Card>

      <Card padded={false}>
        <div style={{ padding: "14px 20px", display: "flex", alignItems: "center", gap: 10 }}>
          <Badge tone="blue">{sims.length} SIM{sims.length !== 1 ? "s" : ""}</Badge>
          <Badge tone="green" dot>{sims.filter((s) => s.active).length} active</Badge>
          <div style={{ flex: 1 }}/>
          <Btn kind="primary" size="sm" onClick={() => setShowAdd(true)} icon={<I.plus size={13}/>}>Add SIM</Btn>
          <Btn kind="ghost" size="sm" onClick={load} icon={<I.history size={13}/>}/>
        </div>

        {loading ? (
          <div style={{ padding: 40, textAlign: "center", color: "var(--ink-3)" }}>Loading…</div>
        ) : sims.length === 0 ? (
          <div style={{ padding: "30px 20px" }}>
            <Empty title="No SIM cards yet" subtitle="Add your first SIM card by port number. The port matches the slot on your Dinstar gateway."/>
          </div>
        ) : (
          <table className="table">
            <thead>
              <tr>
                <th>Port</th>
                <th>Label</th>
                <th>Phone Number</th>
                <th>Carrier</th>
                <th>Prefix</th>
                <th>Status</th>
                <th></th>
              </tr>
            </thead>
            <tbody>
              {sims.map((s) => (
                <tr key={s.id}>
                  <td className="tabular bold">{s.port}</td>
                  <td>{s.label || "—"}</td>
                  <td style={{ fontFamily: "var(--font-mono)", fontSize: 12 }}>{s.phone_number || "—"}</td>
                  <td>{s.carrier || "—"}</td>
                  <td className="tabular">{s.prefix || "—"}</td>
                  <td>
                    <Badge tone={s.active ? "green" : "gray"} dot>{s.active ? "Active" : "Inactive"}</Badge>
                  </td>
                  <td>
                    <div style={{ display: "flex", gap: 6 }}>
                      <Btn kind="ghost" size="sm" onClick={() => toggleActive(s)}>
                        {s.active ? "Disable" : "Enable"}
                      </Btn>
                      <Btn kind="ghost" size="sm" onClick={() => deleteSim(s)} style={{ color: "var(--err)" }}>
                        <I.trash size={12}/>
                      </Btn>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </Card>

      {showAdd && <AddSimModal onClose={() => setShowAdd(false)} onAdded={() => { setShowAdd(false); load(); }}/>}
    </div>
  );
}

function AddSimModal({ onClose, onAdded }) {
  const [form, setForm] = React.useState({
    port: "", label: "", phone_number: "", carrier: "", prefix: "", notes: "",
  });
  const [submitting, setSubmitting] = React.useState(false);
  const [err, setErr] = React.useState(null);

  const submit = async (e) => {
    e.preventDefault();
    setErr(null);
    if (!form.port) return setErr("Port number required.");
    setSubmitting(true);
    const r = await VoaisAPI.post("/api/telephony/sims", form);
    setSubmitting(false);
    if (r.ok) onAdded();
    else      setErr(r.data?.msg || "Failed to add SIM.");
  };

  return (
    <Modal title="Add SIM card" onClose={onClose} width={520}>
      <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="Port *" hint="Slot number on your Dinstar gateway (e.g. 30, 31)">
          <input className="input" type="number" autoFocus placeholder="30" value={form.port} onChange={(e) => setForm({ ...form, port: e.target.value })}/>
        </Field>
        <Field label="Label">
          <input className="input" placeholder="e.g. Airtel Lucknow" value={form.label} onChange={(e) => setForm({ ...form, label: e.target.value })}/>
        </Field>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
          <Field label="Phone number">
            <input className="input" placeholder="+919876543210" value={form.phone_number} onChange={(e) => setForm({ ...form, phone_number: e.target.value })}/>
          </Field>
          <Field label="Carrier">
            <input className="input" placeholder="Airtel / Jio / Vi" value={form.carrier} onChange={(e) => setForm({ ...form, carrier: e.target.value })}/>
          </Field>
        </div>
        <Field label="Routing prefix" hint="Auto-generated if blank (e.g. '7030' for port 30)">
          <input className="input" placeholder="7030" value={form.prefix} onChange={(e) => setForm({ ...form, prefix: 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 ? "Adding…" : "Add SIM"}
          </Btn>
        </div>
      </form>
    </Modal>
  );
}

// ── Advanced tab ────────────────────────────────────────────────────────
function AdvancedTab() {
  return (
    <Card>
      <CardHead title="Advanced settings"/>
      <div style={{ color: "var(--ink-3)", fontSize: 13, lineHeight: 1.6, maxWidth: 520 }}>
        <p>Advanced configuration like DNC list, calling hours, TRAI compliance, and webhook settings will be available here in Phase 7.</p>
        <p style={{ marginTop: 14 }}>For now, you can manage:</p>
        <div style={{ marginTop: 10, display: "flex", flexDirection: "column", gap: 8 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
            <I.check size={14} stroke="var(--ok)"/>
            <span><b>Profile</b> — your name, phone, title</span>
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
            <I.check size={14} stroke="var(--ok)"/>
            <span><b>Telephony</b> — your Asterisk PBX, ARI, GSM gateway, recording</span>
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
            <I.check size={14} stroke="var(--ok)"/>
            <span><b>SIM Cards</b> — your Dinstar GSM ports</span>
          </div>
        </div>

        <div style={{ marginTop: 24, padding: 16, background: "var(--surface-2)", borderRadius: 10 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 6 }}>
            <I.spark size={14} stroke="var(--accent)"/>
            <b style={{ color: "var(--ink)" }}>AI Brain by Hidrogen</b>
          </div>
          <p style={{ margin: 0, fontSize: 12.5, color: "var(--ink-3)", lineHeight: 1.6 }}>
            All AI models — OpenAI Realtime, Gemini Live, Sarvam, Hidrogen — are managed for you. No API keys to bring, no quotas to track. Per-minute pricing covers AI usage.
          </p>
        </div>
      </div>
    </Card>
  );
}

// ── Shared components ───────────────────────────────────────────────────

function StatusDot({ label, on }) {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
      <div style={{ width: 8, height: 8, borderRadius: "50%", background: on ? "var(--ok)" : "var(--err)" }}/>
      <span style={{ fontSize: 12.5, fontWeight: 600 }}>{label}</span>
    </div>
  );
}

function SettingsGroup({ group, form, onChange, secretSnapshot }) {
  const meta = {
    AMI_HOST:    { hint: "IP or hostname of your Asterisk server", placeholder: "192.168.1.100" },
    AMI_PORT:    { hint: "Default: 5038", placeholder: "5038", type: "number" },
    AMI_USER:    { hint: "AMI username from manager.conf", placeholder: "voiceapp" },
    AMI_SECRET:  { hint: "AMI secret from manager.conf", placeholder: "••••••••", secret: true },
    GSM_TRUNK:   { hint: "SIP trunk name pointing to your Dinstar", placeholder: "gsm-trunk" },
    GSM_AI_CONTEXT: { hint: "Dialplan context for AI calls", placeholder: "gsm-ai-out" },
    GSM_DIAL_CONTEXT: { hint: "Dialplan context for plain calls", placeholder: "gsm-out" },
    GSM_DINSTAR_IP: { hint: "Dinstar gateway IP (informational)", placeholder: "192.168.1.200" },
    GSM_PORTS:   { hint: "CSV of port numbers (e.g. 30,31)", placeholder: "30,31" },
    GSM_PREFIX_TEMPLATE: { hint: "Auto-prefix template (e.g. '70' → 7030)", placeholder: "70" },
    ARI_URL:     { hint: "Asterisk REST Interface URL", placeholder: "http://192.168.1.100:8088" },
    ARI_USER:    { placeholder: "voiceari" },
    ARI_PASSWORD: { secret: true, placeholder: "••••••••" },
    ARI_APP:     { hint: "Stasis app name", placeholder: "voicegsm" },
    EXTERNAL_MEDIA_HOST: { hint: "Public IP of VoAIs server (where Asterisk sends RTP)", placeholder: "203.0.113.42" },
    EXTERNAL_MEDIA_PORT: { hint: "UDP port for RTP audio", placeholder: "12000", type: "number" },
    AI_SYSTEM_PROMPT:    { type: "textarea", hint: "Default system prompt for AI calls. Each agent can override this.", placeholder: "You are a helpful, friendly AI assistant on a phone call..." },
    AI_GREETING:         { hint: "Opening line the AI says", placeholder: "Hello! How can I help you today?" },
    AI_DEFAULT_MODEL:    { hint: "Default model ID", placeholder: "gemini-native-latest" },
    AI_PROTECT_GREETING: { hint: "'true' = don't let caller interrupt greeting", placeholder: "true" },
    AI_VAD_SILENCE_MS:   { hint: "Silence before AI replies (ms)", placeholder: "600", type: "number" },
    AI_VAD_THRESHOLD:    { hint: "0-1, higher = less sensitive", placeholder: "0.5" },
    AI_VAD_PREFIX_MS:    { hint: "Extra audio before speech start (ms)", placeholder: "300", type: "number" },
    RECORD_CALLS:        { hint: "'true' or 'false'", placeholder: "true" },
  };

  const icons = {
    ami: <I.server size={16}/>,
    ari: <I.zap size={16}/>,
    gsm: <I.phone size={16}/>,
    ai: <I.bot size={16}/>,
    vad: <I.mic size={16}/>,
    recording: <I.mic size={16}/>,
  };

  return (
    <Card>
      <div style={{ display: "flex", alignItems: "flex-start", gap: 10, marginBottom: 4 }}>
        <div style={{ color: "var(--accent)", marginTop: 2 }}>{icons[group.id] || <I.settings size={16}/>}</div>
        <div style={{ flex: 1 }}>
          <h3 style={{ margin: 0, fontSize: 15, fontWeight: 600 }}>{group.label}</h3>
          {group.description && (
            <p style={{ margin: "4px 0 0", fontSize: 12, color: "var(--ink-3)", lineHeight: 1.5 }}>{group.description}</p>
          )}
        </div>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: group.keys.some((k) => meta[k]?.type === "textarea") ? "1fr" : "1fr 1fr", gap: 14, marginTop: 16 }}>
        {group.keys.map((key) => {
          const m = meta[key] || {};
          const isSecret = m.secret;
          const val = form[key] ?? "";
          const isSet = isSecret && secretSnapshot[key] === "set" && val === "set";

          if (m.type === "textarea") {
            return (
              <Field key={key} label={friendlyLabel(key)} hint={m.hint}>
                <textarea
                  className="textarea"
                  rows={3}
                  placeholder={m.placeholder}
                  value={isSet ? "" : val}
                  onChange={(e) => onChange(key, e.target.value)}
                />
                {isSet && <div style={{ fontSize: 11, color: "var(--ok)", marginTop: 4 }}>Currently set. Leave blank to keep.</div>}
              </Field>
            );
          }

          return (
            <Field key={key} label={friendlyLabel(key)} hint={m.hint}>
              <input
                className="input"
                type={isSecret ? "password" : (m.type === "number" ? "number" : "text")}
                placeholder={isSet ? "••• saved — leave blank to keep •••" : (m.placeholder || "")}
                value={isSet ? "" : val}
                onChange={(e) => onChange(key, e.target.value)}
              />
              {isSet && <div style={{ fontSize: 11, color: "var(--ok)", marginTop: 4 }}>Currently set. Leave blank to keep.</div>}
            </Field>
          );
        })}
      </div>
    </Card>
  );
}

function friendlyLabel(key) {
  const overrides = {
    AMI_HOST: "Asterisk host",
    AMI_PORT: "AMI port",
    AMI_USER: "AMI username",
    AMI_SECRET: "AMI secret",
    ARI_URL: "ARI URL",
    ARI_USER: "ARI username",
    ARI_PASSWORD: "ARI password",
    ARI_APP: "Stasis app name",
    EXTERNAL_MEDIA_HOST: "Public IP (for RTP)",
    EXTERNAL_MEDIA_PORT: "RTP port",
    GSM_TRUNK: "Trunk name",
    GSM_AI_CONTEXT: "AI dialplan context",
    GSM_DIAL_CONTEXT: "Plain-dial context",
    GSM_DINSTAR_IP: "Dinstar IP",
    GSM_PORTS: "GSM port numbers",
    GSM_PREFIX_TEMPLATE: "Prefix template",
    AI_SYSTEM_PROMPT: "Default system prompt",
    AI_GREETING: "Default greeting",
    AI_DEFAULT_MODEL: "Default AI model",
    AI_PROTECT_GREETING: "Protect greeting from interruption",
    AI_VAD_SILENCE_MS: "Silence threshold (ms)",
    AI_VAD_THRESHOLD: "VAD threshold (0-1)",
    AI_VAD_PREFIX_MS: "Prefix padding (ms)",
    RECORD_CALLS: "Record calls",
  };
  return overrides[key] || key.replace(/_/g, " ").toLowerCase().replace(/\b\w/g, (c) => c.toUpperCase());
}

window.SettingsScreen = SettingsScreen;
