/* global React, Icon, Chip, Button, Avatar, api */

const SRC_ICON = {
  WhatsApp: "message-circle", Facebook: "facebook", Website: "globe",
  Referral: "users", "Walk-in": "user", Other: "user",
};

const STAGE_OPTIONS = [
  { value: "new",       label: "New"       },
  { value: "contacted", label: "Contacted" },
  { value: "qualified", label: "Qualified" },
  { value: "converted", label: "Converted" },
  { value: "lost",      label: "Lost"      },
];

const STAGE_KIND = { new: "default", contacted: "info", qualified: "warning", converted: "success", lost: "danger" };

/* ── Convert-to-engagement modal ─────────────────────── */
function ConvertModal({ lead, onClose, onConverted }) {
  const [services,   setServices]   = React.useState([]);
  const [customers,  setCustomers]  = React.useState([]);
  const [form, setForm] = React.useState({
    useExisting:   false,
    customerId:    "",
    custType:      "individual",
    firstName:     (lead.name || "").split(" ")[0],
    lastName:      (lead.name || "").split(" ").slice(1).join(" "),
    companyName:   lead.name || "",
    phone:         lead.phone || "",
    email:         lead._raw?.email || "",
    serviceId:     "",
    dueDate:       "",
    quoted:        "",
  });
  const [saving, setSaving] = React.useState(false);
  const [error,  setError]  = React.useState("");

  React.useEffect(() => {
    Promise.all([api.get("/services"), api.get("/customers")])
      .then(([sRes, cRes]) => {
        const svcs = sRes.data || [];
        setServices(svcs);
        setCustomers(cRes.data || []);
        const match = svcs.find(s => lead.svc && lead.svc.startsWith(s.name));
        if (match) setForm(f => ({ ...f, serviceId: match._id }));
      })
      .catch(() => {});
  }, []);

  const set = key => ev => setForm(f => ({ ...f, [key]: ev.target.value }));

  async function handleSubmit(ev) {
    ev.preventDefault();
    if (!form.serviceId) { setError("Select a service."); return; }
    if (form.useExisting && !form.customerId) { setError("Select an existing customer."); return; }
    if (!form.useExisting && !form.phone.trim()) { setError("Phone is required."); return; }
    if (!form.useExisting && !form.email.trim()) { setError("Email is required to create a customer."); return; }
    setSaving(true); setError("");
    try {
      let customerId = form.customerId;
      if (!form.useExisting) {
        const cRes = await api.post("/customers", {
          type:        form.custType,
          firstName:   form.custType === "individual" ? form.firstName : "",
          lastName:    form.custType === "individual" ? form.lastName  : "",
          companyName: form.custType === "organisation" ? form.companyName : "",
          phone:       form.phone.trim(),
          email:       form.email.trim(),
        });
        customerId = cRes.data._id;
      }
      const engRes = await api.post("/engagements", {
        customer:  customerId,
        service:   form.serviceId,
        status:    "active",
        quoted:    form.quoted ? Number(form.quoted) : 0,
        dueDate:   form.dueDate || undefined,
      });
      await api.put("/leads/" + lead._id, { status: "converted" });
      onConverted(engRes.data);
    } catch (err) {
      setError(err.message || "Conversion failed.");
      setSaving(false);
    }
  }

  function custLabel(c) {
    return c.type === "organisation"
      ? c.companyName
      : [c.firstName, c.lastName].filter(Boolean).join(" ") || c.email || "—";
  }

  return (
    <>
      <div className="scrim" onClick={onClose} style={{ zIndex: 300 }} />
      <div className="modal" role="dialog" aria-modal="true" style={{ zIndex: 301 }}>
        <div className="modal-head">
          <div>
            <div className="eyebrow" style={{ marginBottom: 4 }}>Convert lead</div>
            <h2 style={{ margin: 0, fontSize: 18, fontWeight: 600 }}>Open engagement for {lead.name}</h2>
          </div>
          <button className="icon-btn" onClick={onClose}><Icon name="x" size={18} /></button>
        </div>
        <form onSubmit={handleSubmit} className="modal-body">
          {error && (
            <div style={{ background: "var(--danger-50)", color: "var(--danger-700)", border: "1px solid var(--danger-200)", borderRadius: 6, padding: "8px 12px", fontSize: 13 }}>
              {error}
            </div>
          )}

          {/* Customer */}
          <div style={{ background: "var(--ink-50)", border: "1px solid var(--border-subtle)", borderRadius: 8, padding: "12px 14px", marginBottom: 4 }}>
            <div style={{ display: "flex", gap: 16, marginBottom: 10 }}>
              <label style={{ display: "flex", alignItems: "center", gap: 6, fontSize: 13, cursor: "pointer" }}>
                <input type="radio" checked={!form.useExisting} onChange={() => setForm(f => ({ ...f, useExisting: false }))} />
                Create new customer from lead
              </label>
              <label style={{ display: "flex", alignItems: "center", gap: 6, fontSize: 13, cursor: "pointer" }}>
                <input type="radio" checked={form.useExisting} onChange={() => setForm(f => ({ ...f, useExisting: true }))} />
                Link to existing customer
              </label>
            </div>

            {form.useExisting ? (
              <div className="field" style={{ margin: 0 }}>
                <label>Customer</label>
                <select value={form.customerId} onChange={set("customerId")}>
                  <option value="">Select customer…</option>
                  {customers.map(c => <option key={c._id} value={c._id}>{custLabel(c)}</option>)}
                </select>
              </div>
            ) : (
              <>
                <div style={{ display: "flex", gap: 10, marginBottom: 10 }}>
                  {["individual", "organisation"].map(t => (
                    <label key={t} style={{ display: "flex", alignItems: "center", gap: 5, fontSize: 12.5, cursor: "pointer", fontWeight: form.custType === t ? 600 : 400 }}>
                      <input type="radio" value={t} checked={form.custType === t} onChange={set("custType")} />
                      {t === "individual" ? "Individual" : "Organisation"}
                    </label>
                  ))}
                </div>
                {form.custType === "individual" ? (
                  <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
                    <div className="field" style={{ margin: 0 }}>
                      <label>First name</label>
                      <input value={form.firstName} onChange={set("firstName")} />
                    </div>
                    <div className="field" style={{ margin: 0 }}>
                      <label>Last name</label>
                      <input value={form.lastName} onChange={set("lastName")} />
                    </div>
                  </div>
                ) : (
                  <div className="field" style={{ margin: 0, marginBottom: 10 }}>
                    <label>Company name</label>
                    <input value={form.companyName} onChange={set("companyName")} />
                  </div>
                )}
                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10, marginTop: 10 }}>
                  <div className="field" style={{ margin: 0 }}>
                    <label>Phone</label>
                    <input value={form.phone} onChange={set("phone")} placeholder="+971 50 000 0000" />
                  </div>
                  <div className="field" style={{ margin: 0 }}>
                    <label>Email</label>
                    <input type="email" value={form.email} onChange={set("email")} placeholder="email@example.com" />
                  </div>
                </div>
              </>
            )}
          </div>

          {/* Service + details */}
          <div className="field">
            <label>Service</label>
            <select value={form.serviceId} onChange={set("serviceId")}>
              <option value="">Select a service…</option>
              {services.map(s => <option key={s._id} value={s._id}>{s.name}</option>)}
            </select>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
            <div className="field">
              <label>Quoted (AED) <span style={{ color: "var(--fg-4)", fontWeight: 400 }}>(optional)</span></label>
              <input type="number" min="0" placeholder="0" value={form.quoted} onChange={set("quoted")} />
            </div>
            <div className="field">
              <label>Due date <span style={{ color: "var(--fg-4)", fontWeight: 400 }}>(optional)</span></label>
              <input type="date" value={form.dueDate} onChange={set("dueDate")} />
            </div>
          </div>

          <div className="modal-footer">
            <Button variant="secondary" type="button" onClick={onClose}>Cancel</Button>
            <Button type="submit" icon="arrow-right" disabled={saving}>{saving ? "Converting…" : "Convert & open"}</Button>
          </div>
        </form>
      </div>
    </>
  );
}

/* ── Lead drawer ─────────────────────────────────────── */
function LeadDrawer({ lead, onClose, onConvert, onLeadUpdated }) {
  const [fullLead,   setFullLead]   = React.useState(null);
  const [stage,      setStage]      = React.useState(lead ? lead.stage : "new");
  const [savingStage, setSavingStage] = React.useState(false);
  const [showConvert, setShowConvert] = React.useState(false);
  const [agents,     setAgents]     = React.useState([]);
  const [showReassign, setShowReassign] = React.useState(false);

  React.useEffect(() => {
    if (!lead) return;
    setStage(lead.stage);
    setFullLead(null);
    api.get("/leads/" + lead._id)
      .then(res => setFullLead(res.data))
      .catch(() => {});
    api.get("/users?status=active")
      .then(res => setAgents(res.data || []))
      .catch(() => {});
  }, [lead?._id]);

  if (!lead) return null;

  const display = fullLead ? {
    name:   lead.name,
    phone:  fullLead.phone || lead.phone,
    email:  fullLead.email || "",
    src:    lead.src,
    svc:    fullLead.service || lead.svc,
    stage:  fullLead.status || stage,
    when:   lead.when,
    msg:    fullLead.notes || lead.msg || "",
    agent:  fullLead.assignedTo ? fullLead.assignedTo.name : lead.agent,
  } : {
    name:  lead.name,
    phone: lead.phone,
    email: "",
    src:   lead.src,
    svc:   lead.svc,
    stage, when: lead.when,
    msg:   lead.msg || "",
    agent: lead.agent,
  };

  async function changeStage(newStage) {
    setStage(newStage);
    setSavingStage(true);
    try {
      const res = await api.put("/leads/" + lead._id, { status: newStage });
      if (onLeadUpdated) onLeadUpdated(res.data);
    } catch (_) {}
    finally { setSavingStage(false); }
  }

  async function markLost() {
    if (stage === "lost") return;
    await changeStage("lost");
    onClose();
  }

  async function reassign(userId) {
    setShowReassign(false);
    try {
      const res = await api.put("/leads/" + lead._id, { assignedTo: userId });
      setFullLead(res.data);
      if (onLeadUpdated) onLeadUpdated(res.data);
    } catch (_) {}
  }

  function handleConverted(rawEng) {
    setShowConvert(false);
    onClose();
    if (onConvert) onConvert(rawEng);
  }

  return (
    <>
      {showConvert && (
        <ConvertModal
          lead={{ ...lead, _raw: fullLead || lead._raw }}
          onClose={() => setShowConvert(false)}
          onConverted={handleConverted}
        />
      )}

      <div className="scrim" onClick={onClose} />
      <aside className="drawer">
        {/* Header */}
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "16px 22px", borderBottom: "1px solid var(--border-subtle)" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
            <Avatar name={display.name} />
            <div>
              <div style={{ fontWeight: 600, fontSize: 15 }}>{display.name}</div>
              <div style={{ fontSize: 12, color: "var(--fg-3)", fontFamily: "var(--font-mono)" }}>{display.phone}</div>
            </div>
          </div>
          <button className="icon-btn" onClick={onClose}><Icon name="x" size={18} /></button>
        </div>

        {/* Body */}
        <div style={{ padding: 22, overflow: "auto", flex: 1 }}>

          {/* Meta grid */}
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14, marginBottom: 20 }}>
            <div>
              <div className="eyebrow" style={{ fontSize: 10 }}>Source</div>
              <div style={{ display: "flex", gap: 6, alignItems: "center", marginTop: 4, fontSize: 13.5 }}>
                <Icon name={SRC_ICON[display.src] || "user"} size={14} /> {display.src}
              </div>
            </div>
            <div>
              <div className="eyebrow" style={{ fontSize: 10 }}>Service interest</div>
              <div style={{ marginTop: 4, fontSize: 13.5 }}>{display.svc || "—"}</div>
            </div>
            <div>
              <div className="eyebrow" style={{ fontSize: 10 }}>Stage</div>
              <div style={{ marginTop: 6 }}>
                <select
                  value={stage}
                  onChange={e => changeStage(e.target.value)}
                  disabled={savingStage}
                  style={{
                    fontFamily: "var(--font-sans)", fontSize: 12.5, fontWeight: 500,
                    padding: "5px 10px", borderRadius: 6, border: "1px solid var(--border-strong)",
                    background: "#fff", color: "var(--fg-1)", outline: "none", cursor: "pointer",
                    opacity: savingStage ? 0.6 : 1,
                  }}>
                  {STAGE_OPTIONS.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
                </select>
              </div>
            </div>
            <div>
              <div className="eyebrow" style={{ fontSize: 10 }}>Received</div>
              <div style={{ marginTop: 4, fontSize: 13.5 }}>{display.when}</div>
            </div>
            {display.email && (
              <div style={{ gridColumn: "span 2" }}>
                <div className="eyebrow" style={{ fontSize: 10 }}>Email</div>
                <div style={{ marginTop: 4, fontSize: 13, fontFamily: "var(--font-mono)", color: "var(--fg-2)" }}>{display.email}</div>
              </div>
            )}
            <div>
              <div className="eyebrow" style={{ fontSize: 10 }}>Assigned to</div>
              <div style={{ marginTop: 4, fontSize: 13.5 }}>
                {display.agent
                  ? <Chip kind="brand" dot={false}>{display.agent}</Chip>
                  : <span style={{ color: "var(--fg-4)" }}>Unassigned</span>}
              </div>
            </div>
          </div>

          {/* Notes / original message */}
          {display.msg && (
            <>
              <div className="eyebrow" style={{ fontSize: 10, marginBottom: 6 }}>Notes</div>
              <div style={{ padding: "12px 14px", background: "var(--ink-50)", borderLeft: "3px solid var(--brand-burgundy)", borderRadius: "0 6px 6px 0", marginBottom: 22, fontSize: 13.5, lineHeight: 1.5 }}>
                {display.msg}
              </div>
            </>
          )}

          {/* Reassign dropdown */}
          {showReassign && (
            <div style={{ background: "#fff", border: "1px solid var(--border-strong)", borderRadius: 8, padding: 12, marginBottom: 16, boxShadow: "0 4px 16px rgba(0,0,0,.08)" }}>
              <div style={{ fontSize: 12, fontWeight: 600, color: "var(--fg-3)", marginBottom: 8, textTransform: "uppercase", letterSpacing: "0.07em" }}>
                Assign to
              </div>
              {agents.length === 0
                ? <div style={{ fontSize: 13, color: "var(--fg-3)" }}>No team members found.</div>
                : agents.map(u => (
                  <div key={u._id}
                    onClick={() => reassign(u._id)}
                    style={{ display: "flex", alignItems: "center", gap: 10, padding: "8px 4px", cursor: "pointer", borderRadius: 6, fontSize: 13 }}
                    onMouseEnter={e => e.currentTarget.style.background = "var(--ink-50)"}
                    onMouseLeave={e => e.currentTarget.style.background = "transparent"}>
                    <Avatar name={u.name} />
                    <div>
                      <div style={{ fontWeight: 500 }}>{u.name}</div>
                      {u.role && <div style={{ fontSize: 11, color: "var(--fg-3)" }}>{u.role.name || ""}</div>}
                    </div>
                  </div>
                ))
              }
              <button className="btn btn-ghost btn-sm" onClick={() => setShowReassign(false)} style={{ marginTop: 6 }}>Cancel</button>
            </div>
          )}

          {/* Quick actions */}
          <div className="eyebrow" style={{ fontSize: 10, marginBottom: 8 }}>Quick actions</div>
          <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
            <Button variant="secondary" icon="message-circle" size="sm">Reply via WhatsApp</Button>
            <Button variant="secondary" icon="phone" size="sm">Log call</Button>
            <Button variant="secondary" icon="user-cog" size="sm" onClick={() => setShowReassign(v => !v)}>Reassign</Button>
            {stage !== "lost" && (
              <Button variant="secondary" icon="archive" size="sm" onClick={markLost}>Mark lost</Button>
            )}
          </div>
        </div>

        {/* Footer */}
        <div style={{ padding: 16, borderTop: "1px solid var(--border-subtle)", display: "flex", gap: 8, justifyContent: "flex-end", background: "var(--ink-50)" }}>
          <Button variant="secondary" onClick={onClose}>Close</Button>
          {stage !== "converted" && stage !== "lost" && (
            <Button icon="arrow-right" onClick={() => setShowConvert(true)}>Convert to engagement</Button>
          )}
        </div>
      </aside>
    </>
  );
}

Object.assign(window, { LeadDrawer });
