const { useState, useEffect } = React;

/* CRM email — compose-from-Gmail modal + per-account email timeline.
 * Uses the gmail-oauth / gmail-send edge functions (per-user Gmail OAuth).
 * Exposes window.CrmEmailCompose and window.CrmEmailTimeline. */

const EM_INPUT = { width: "100%", padding: "8px 10px", border: "1px solid var(--border-1, #d8d8d8)", borderRadius: 7, fontSize: "var(--fs-base, 13px)", background: "var(--bg-1, #fff)", color: "var(--fg-1, #111)", boxSizing: "border-box" };
const firstName = (n) => (n || "").trim().split(/\s+/)[0] || "";
const merge = (s, ctx) => (s || "")
  .replace(/\{\{\s*first_name\s*\}\}/gi, firstName(ctx.name))
  .replace(/\{\{\s*name\s*\}\}/gi, ctx.name || "")
  .replace(/\{\{\s*company\s*\}\}/gi, ctx.company || "");
const esc = (s) => (s || "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");

function CrmEmailCompose({ recipient, orgId, orgName, dealId, onClose }) {
  const ctx = React.useContext(window.CrmContext) || {};
  const toast = ctx.toast || (() => {});
  const Ico = window.CrmIco || {};
  const c = window.ContactIQ && window.ContactIQ.client;
  const authHeaders = async () => {
    try { const { data } = await c.auth.getSession(); const t = data && data.session && data.session.access_token; return t ? { Authorization: "Bearer " + t } : {}; } catch { return {}; }
  };
  const [accounts, setAccounts] = useState(null);
  const [templates, setTemplates] = useState([]);
  const [to, setTo] = useState((recipient && recipient.to) || "");
  const [subject, setSubject] = useState("");
  const [body, setBody] = useState("");
  const [sending, setSending] = useState(false);
  const [connecting, setConnecting] = useState(false);

  useEffect(() => {
    if (!c) { setAccounts([]); return; }
    c.rpc("crm_email_accounts_list").then(({ data }) => setAccounts(data || [])).catch(() => setAccounts([]));
    c.from("crm_email_templates").select("id,name,subject,body").order("name").then(({ data }) => setTemplates(data || [])).catch(() => {});
    const onKey = (e) => { if (e.key === "Escape") onClose && onClose(); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, []);

  const connected = accounts && accounts.find((a) => a.status === "active");

  const connectGmail = async () => {
    if (!c) return;
    setConnecting(true);
    try {
      const { data, error } = await c.functions.invoke("gmail-oauth", { body: {}, headers: await authHeaders() });
      if (error || !data || !data.url) { toast("Couldn't start Gmail connect"); setConnecting(false); return; }
      window.open(data.url, "_blank");
      let n = 0;
      const poll = setInterval(async () => {
        n++;
        const { data: list } = await c.rpc("crm_email_accounts_list");
        if (list && list.find((a) => a.status === "active")) { setAccounts(list); setConnecting(false); clearInterval(poll); toast("Gmail connected"); }
        else if (n > 48) { clearInterval(poll); setConnecting(false); }
      }, 2500);
    } catch { setConnecting(false); }
  };

  const applyTemplate = (e) => {
    const t = templates.find((x) => String(x.id) === String(e.target.value));
    if (!t) return;
    const mc = { name: (recipient && recipient.name) || "", company: orgName || "" };
    setSubject(merge(t.subject, mc));
    setBody(merge(t.body, mc));
  };

  const send = async () => {
    if (!to.trim() || !subject.trim() || !body.trim()) { toast("Add a recipient, subject, and message"); return; }
    setSending(true);
    try {
      const html = '<div style="font:14px/1.5 Arial,sans-serif;color:#222">' + esc(body).replace(/\n/g, "<br>") + "</div>";
      const { data, error } = await c.functions.invoke("gmail-send", { body: { to: to.trim(), subject: subject.trim(), body: html, org_id: orgId || null, deal_id: dealId || null, person_id: (recipient && recipient.person_id) || null }, headers: await authHeaders() });
      let reason = (data && data.error) || null;
      if (error && !reason) { try { const b = await error.context.json(); reason = b.error || b.detail || error.message; } catch { reason = error.message; } }
      if (reason) { toast("Send failed: " + reason); setSending(false); return; }
      toast("Email sent");
      onClose && onClose(true);
    } catch { toast("Send failed"); setSending(false); }
  };

  return (
    <div className="modal-overlay" onClick={() => onClose && onClose()}>
      <div className="modal" onClick={(e) => e.stopPropagation()} style={{ maxWidth: 540 }}>
        <div className="modal-head">
          <div className="col" style={{ gap: 2, minWidth: 0 }}>
            <span className="eyebrow">New email</span>
            <span style={{ fontWeight: 700, fontSize: 15 }}>{(recipient && recipient.name) || to || "Compose"}</span>
            {recipient && recipient.title && <span className="src" style={{ marginTop: 2 }}>{recipient.title}</span>}
          </div>
          <button className="dr-close" onClick={() => onClose && onClose()}>{Ico.X ? <Ico.X /> : "✕"}</button>
        </div>
        <div className="modal-body">
          {accounts == null
            ? <div className="muted">Loading…</div>
            : !connected
            ? <div style={{ textAlign: "center", padding: "12px 0" }}>
                <div className="muted" style={{ marginBottom: 12 }}>Connect your Gmail to send email from the CRM. It sends as you, and replies come to your inbox.</div>
                <button className="btn btn-primary" disabled={connecting} onClick={connectGmail}>{connecting ? "Waiting for Google…" : "Connect Gmail"}</button>
              </div>
            : <>
                <div className="src" style={{ marginBottom: 8 }}>Sending as <strong>{connected.email_address}</strong></div>
                <div className="col" style={{ gap: 8 }}>
                  <input type="email" value={to} onChange={(e) => setTo(e.target.value)} placeholder="recipient@email.com" style={EM_INPUT} />
                  {templates.length > 0 && (
                    <select onChange={applyTemplate} defaultValue="" style={EM_INPUT}>
                      <option value="" disabled>Insert a template…</option>
                      {templates.map((t) => <option key={t.id} value={t.id}>{t.name}</option>)}
                    </select>
                  )}
                  <input value={subject} onChange={(e) => setSubject(e.target.value)} placeholder="Subject" style={EM_INPUT} />
                  <textarea value={body} onChange={(e) => setBody(e.target.value)} placeholder="Write your message…" rows={8} style={{ ...EM_INPUT, resize: "vertical", fontFamily: "inherit" }} />
                </div>
              </>}
        </div>
        <div className="modal-foot">
          <button className="btn btn-sm" onClick={() => onClose && onClose()}>Cancel</button>
          {connected && <button className="btn btn-primary btn-sm" disabled={sending} onClick={send}>{sending ? "Sending…" : "Send"}</button>}
        </div>
      </div>
    </div>
  );
}
window.CrmEmailCompose = CrmEmailCompose;

function CrmEmailTimeline({ orgId }) {
  const c = window.ContactIQ && window.ContactIQ.client;
  const [emails, setEmails] = useState(null);
  useEffect(() => {
    if (!c || !orgId) { setEmails([]); return; }
    c.from("crm_emails").select("id,direction,to_email,from_email,subject,status,open_count,sent_at")
      .eq("org_id", orgId).order("sent_at", { ascending: false }).limit(25)
      .then(({ data }) => setEmails(data || [])).catch(() => setEmails([]));
  }, [orgId]);
  if (!emails || !emails.length) return null;
  const dt = (s) => { try { return new Date(s).toLocaleDateString(); } catch { return ""; } };
  return (
    <section className="card side-card">
      <div className="card-head"><span className="ch-title">Emails</span><span className="pill" style={{ padding: "1px 7px" }}><span className="fact">{emails.length}</span></span></div>
      {emails.map((e) => (
        <div className="contact-row" key={e.id}>
          <div className="contact-main">
            <div className="contact-name" style={{ fontSize: "var(--fs-base)" }}>{e.subject || "(no subject)"}</div>
            <div className="contact-title">{e.direction === "out" ? "to " + (e.to_email || "") : "from " + (e.from_email || "")} · {dt(e.sent_at)}{e.open_count > 0 ? " · opened" : ""}</div>
          </div>
          <span className="pill" style={{ alignSelf: "center", color: e.status === "sent" ? "var(--green)" : e.status === "failed" ? "var(--red)" : "var(--fg-3)" }}>{e.status}</span>
        </div>
      ))}
    </section>
  );
}
window.CrmEmailTimeline = CrmEmailTimeline;
