// ============================================================================
// public/screens/contacts.jsx — Contacts manager (segments rail + table)
// ----------------------------------------------------------------------------
//   • Top: KPI strip from /api/contacts/segments
//   • Left: segments rail (filter by status / last_outcome)
//   • Center: search + table with bulk-select
//   • Modals: CSV upload, manual add, phonebook management
// ============================================================================

function ContactsScreen({ go }) {
  const [segments, setSegments]   = React.useState(null);
  const [contacts, setContacts]   = React.useState([]);
  const [total, setTotal]         = React.useState(0);
  const [loading, setLoading]     = React.useState(true);
  const [filter, setFilter]       = React.useState("all");     // segment id
  const [phonebook, setPhonebook] = React.useState("");        // phonebook id
  const [phonebooks, setPhonebooks] = React.useState([]);
  const [q, setQ]                 = React.useState("");
  const [selected, setSelected]   = React.useState(new Set());
  const [showUpload, setShowUpload] = React.useState(false);
  const [showAdd, setShowAdd]     = React.useState(false);

  // Fetch list + segments together.
  const reload = React.useCallback(() => {
    setLoading(true);
    const params = new URLSearchParams();
    if (filter !== "all" && filter !== "completed") params.append("status", filter);
    if (phonebook) params.append("phonebook", phonebook);
    if (q.trim())  params.append("q", q.trim());

    Promise.all([
      VoaisAPI.get("/api/contacts?" + params.toString() + "&limit=100"),
      VoaisAPI.get("/api/contacts/segments"),
      VoaisAPI.get("/api/contacts/phonebooks"),
    ]).then(([list, seg, pb]) => {
      setContacts(list.ok && list.data?.ok ? list.data.contacts : []);
      setTotal(   list.ok && list.data?.ok ? list.data.total    : 0);
      setSegments(seg.ok  && seg.data?.ok  ? seg.data.segments  : null);
      setPhonebooks(pb.ok && pb.data?.ok   ? pb.data.phonebooks : []);
      setLoading(false);
    });
  }, [filter, phonebook, q]);

  // Debounce search.
  React.useEffect(() => {
    const id = setTimeout(reload, q ? 250 : 0);
    return () => clearTimeout(id);
  }, [reload, q]);

  const toggle = (id) => {
    const s = new Set(selected);
    s.has(id) ? s.delete(id) : s.add(id);
    setSelected(s);
  };
  const toggleAll = () => {
    if (selected.size === contacts.length) setSelected(new Set());
    else setSelected(new Set(contacts.map((c) => c.id)));
  };

  const bulkAction = async (action) => {
    if (!selected.size) return;
    if (action === "delete" && !confirm(`Delete ${selected.size} contacts?`)) return;
    const r = await VoaisAPI.post("/api/contacts/bulk-action", { ids: [...selected], action });
    if (!r.ok) { alert(r.data?.msg || "Bulk action failed."); return; }
    setSelected(new Set());
    reload();
  };

  // ── KPIs from segments ────────────────────────────────────────────
  const k = segments || {};
  const totalC      = Number(k.total      || 0);
  const pendingC    = Number(k.pending    || 0);
  const dialedToday = Number(k.dialed_today || 0);
  const dncC        = Number(k.dnc        || 0);

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

      {/* KPI strip */}
      <div className="kpi-grid">
        <Card className="kpi-card">
          <div className="kpi-label">Total contacts</div>
          <div className="kpi-value tabular">{totalC.toLocaleString("en-IN")}</div>
          <div className="kpi-foot"><span style={{ color: "var(--accent)" }}>●</span> across {phonebooks.length} phonebook{phonebooks.length === 1 ? "" : "s"}</div>
        </Card>
        <Card className="kpi-card">
          <div className="kpi-label">Pending dial</div>
          <div className="kpi-value tabular">{pendingC.toLocaleString("en-IN")}</div>
          <div className="kpi-foot"><span style={{ color: "var(--viz-yellow)" }}>●</span> {totalC > 0 ? `${Math.round(pendingC / totalC * 100)}% of total` : "—"}</div>
        </Card>
        <Card className="kpi-card">
          <div className="kpi-label">Dialed today</div>
          <div className="kpi-value tabular">{dialedToday.toLocaleString("en-IN")}</div>
          <div className="kpi-foot"><span style={{ color: "var(--viz-green)" }}>●</span> last 24 hours</div>
        </Card>
        <Card className="kpi-card">
          <div className="kpi-label">DND / Opted out</div>
          <div className="kpi-value tabular">{dncC.toLocaleString("en-IN")}</div>
          <div className="kpi-foot"><span style={{ color: "var(--err)" }}>●</span> {totalC > 0 ? `${(dncC / totalC * 100).toFixed(2)}% of total` : "—"}</div>
        </Card>
      </div>

      {/* Layout: segments rail | table */}
      <div className="mobile-stack" style={{ display: "grid", gridTemplateColumns: "260px 1fr", gap: "var(--gap-grid)" }}>

        {/* Segments rail */}
        <Card padded={false}>
          <div style={{ padding: "14px 16px", borderBottom: "1px solid var(--line)" }}>
            <h3 style={{ margin: 0, fontSize: 13, fontWeight: 600 }}>Segments</h3>
          </div>
          <div style={{ padding: 8, display: "flex", flexDirection: "column", gap: 1 }}>
            <SegmentItem icon={<I.contacts size={14}/>} label="All contacts"  count={totalC}                value="all"          active={filter} onClick={setFilter}/>
            <SegmentItem icon={<I.history  size={14}/>} label="Pending"        count={pendingC}              value="pending"      active={filter} onClick={setFilter}/>
            <SegmentItem icon={<I.check    size={14}/>} label="Active"         count={Number(k.active||0)}   value="active"       active={filter} onClick={setFilter}/>
            <SegmentItem icon={<I.shield   size={14}/>} label="DND / Opt-out"  count={dncC}                  value="do_not_call"  active={filter} onClick={setFilter}/>
            <SegmentItem icon={<I.alert    size={14}/>} label="Blocked"        count={Number(k.blocked||0)}  value="blocked"      active={filter} onClick={setFilter}/>
          </div>

          <div style={{ padding: "10px 16px", borderTop: "1px solid var(--line)", borderBottom: "1px solid var(--line)" }}>
            <h3 style={{ margin: 0, fontSize: 13, fontWeight: 600 }}>Phonebooks</h3>
          </div>
          <div style={{ padding: 8, display: "flex", flexDirection: "column", gap: 1, maxHeight: 240, overflowY: "auto" }}>
            <SegmentItem icon={<I.template size={14}/>} label="All phonebooks" count={null} value="" active={phonebook} onClick={setPhonebook}/>
            {phonebooks.map((pb) => (
              <SegmentItem
                key={pb.id} icon={<I.template size={14}/>}
                label={pb.name} count={pb.count}
                value={String(pb.id)} active={phonebook} onClick={setPhonebook}
              />
            ))}
            {phonebooks.length === 0 && (
              <div style={{ padding: "8px 12px", fontSize: 11.5, color: "var(--ink-3)" }}>No phonebooks yet.</div>
            )}
          </div>

          <div style={{ padding: "12px 16px", borderTop: "1px solid var(--line)" }}>
            <Btn kind="primary" size="sm" style={{ width: "100%" }} icon={<I.plus size={13}/>} onClick={() => setShowUpload(true)}>
              Upload CSV
            </Btn>
            <Btn kind="ghost"   size="sm" style={{ width: "100%", marginTop: 6 }} icon={<I.plus size={13}/>} onClick={() => setShowAdd(true)}>
              Add manually
            </Btn>
          </div>
        </Card>

        {/* Table side */}
        <Card padded={false}>
          {/* Search + bulk-action bar */}
          <div style={{ padding: "12px 16px", borderBottom: "1px solid var(--line)", display: "flex", gap: 10, alignItems: "center" }}>
            <div className="search-box" style={{ flex: 1, maxWidth: 340 }}>
              <I.search size={14}/>
              <input placeholder="Search by name, phone, or email…" value={q} onChange={(e) => setQ(e.target.value)}/>
            </div>
            {selected.size > 0 ? (
              <>
                <span style={{ fontSize: 12.5, color: "var(--ink-3)" }}>{selected.size} selected</span>
                <Btn kind="ghost"   size="sm" onClick={() => bulkAction("dnc")}>Mark DNC</Btn>
                <Btn kind="ghost"   size="sm" onClick={() => bulkAction("activate")}>Activate</Btn>
                <Btn kind="ghost"   size="sm" onClick={() => bulkAction("delete")} style={{ color: "var(--err)" }}>Delete</Btn>
              </>
            ) : (
              <span style={{ fontSize: 12.5, color: "var(--ink-3)" }}>{total.toLocaleString("en-IN")} total{q ? " (filtered)" : ""}</span>
            )}
          </div>

          {/* Table */}
          {loading ? (
            <div style={{ padding: 40, textAlign: "center", color: "var(--ink-3)" }}>Loading…</div>
          ) : contacts.length === 0 ? (
            <div style={{ padding: "60px 20px" }}>
              <Empty title={q ? "No matches" : "No contacts yet"} subtitle={q ? "Try a different search term." : "Upload a CSV or add contacts manually to get started."}/>
            </div>
          ) : (
            <table className="table">
              <thead>
                <tr>
                  <th style={{ width: 32 }}>
                    <input type="checkbox" checked={selected.size === contacts.length && contacts.length > 0} onChange={toggleAll}/>
                  </th>
                  <th>Name / Phone</th>
                  <th>Email</th>
                  <th>Phonebook</th>
                  <th>Status</th>
                  <th>Attempts</th>
                  <th>Last contact</th>
                </tr>
              </thead>
              <tbody>
                {contacts.map((c) => (
                  <tr key={c.id} style={{ cursor: "pointer" }}>
                    <td onClick={(e) => e.stopPropagation()}>
                      <input type="checkbox" checked={selected.has(c.id)} onChange={() => toggle(c.id)}/>
                    </td>
                    <td>
                      <div style={{ fontWeight: 600 }}>{c.name || <span style={{ color: "var(--ink-3)" }}>(unnamed)</span>}</div>
                      <div style={{ fontSize: 11.5, color: "var(--ink-3)", marginTop: 2, fontFamily: "var(--font-mono)" }}>{c.phone}</div>
                    </td>
                    <td style={{ fontSize: 12 }}>{c.email || "—"}</td>
                    <td style={{ fontSize: 12 }}>{c.phonebook_name || "—"}</td>
                    <td>
                      <Badge tone={c.status === "active" ? "green" : c.status === "do_not_call" ? "red" : c.status === "blocked" ? "red" : "gray"} dot>
                        {c.status.replace(/_/g, " ")}
                      </Badge>
                    </td>
                    <td className="tabular">{c.attempts || 0}</td>
                    <td style={{ fontSize: 12, color: "var(--ink-3)" }}>
                      {c.last_contacted_at ? new Date(c.last_contacted_at).toLocaleString("en-IN", { dateStyle: "short", timeStyle: "short" }) : "—"}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </Card>
      </div>

      {showUpload && (
        <UploadCsvModal
          phonebooks={phonebooks}
          onClose={() => setShowUpload(false)}
          onUploaded={() => { setShowUpload(false); reload(); }}
        />
      )}
      {showAdd && (
        <AddContactModal
          phonebooks={phonebooks}
          onClose={() => setShowAdd(false)}
          onAdded={() => { setShowAdd(false); reload(); }}
        />
      )}
    </div>
  );
}

// ── Segment row in the rail ─────────────────────────────────────────────
function SegmentItem({ icon, label, count, value, active, onClick }) {
  return (
    <div
      className={`nav-item ${active === value ? "active" : ""}`}
      style={{ padding: "8px 12px", margin: 0, borderRadius: 8 }}
      onClick={() => onClick(value)}
    >
      <span style={{ color: "var(--ink-3)" }}>{icon}</span>
      <span style={{ flex: 1, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{label}</span>
      {count !== null && count !== undefined && (
        <span className="tabular" style={{ fontSize: 11, color: "var(--ink-3)" }}>{Number(count).toLocaleString("en-IN")}</span>
      )}
    </div>
  );
}

// ── Upload CSV modal ────────────────────────────────────────────────────
function UploadCsvModal({ phonebooks, onClose, onUploaded }) {
  const [step, setStep]     = React.useState("pick");  // pick → uploading → done
  const [pbMode, setPbMode] = React.useState(phonebooks.length ? "existing" : "new");
  const [pbId, setPbId]     = React.useState(phonebooks[0]?.id || "");
  const [newPbName, setNewPbName] = React.useState("");
  const [csvText, setCsvText] = React.useState("");
  const [result, setResult]   = React.useState(null);
  const [err, setErr]         = React.useState(null);
  const fileRef = React.useRef(null);

  const onFile = (f) => {
    if (!f) return;
    const reader = new FileReader();
    reader.onload = (e) => setCsvText(String(e.target.result || ""));
    reader.readAsText(f);
  };

  const submit = async () => {
    setErr(null);
    if (!csvText.trim()) return setErr("Choose a CSV file or paste CSV text.");
    let targetPb = pbId;
    if (pbMode === "new") {
      if (!newPbName.trim()) return setErr("Enter a name for the new phonebook.");
      const create = await VoaisAPI.post("/api/contacts/phonebooks", { name: newPbName.trim() });
      if (!create.ok) return setErr(create.data?.msg || "Failed to create phonebook.");
      targetPb = create.data.phonebookId;
    }
    if (!targetPb) return setErr("Pick a phonebook to import into.");

    setStep("uploading");
    const r = await VoaisAPI.post(`/api/contacts/phonebooks/${targetPb}/import-csv`, { csv: csvText });
    if (!r.ok) { setErr(r.data?.msg || "Import failed."); setStep("pick"); return; }
    setResult(r.data);
    setStep("done");
  };

  return (
    <Modal title="Upload contacts CSV" onClose={onClose} width={580}>
      {err && <div className="auth-banner err" style={{ marginBottom: 14 }}><I.alert size={14}/><span>{err}</span></div>}

      {step === "pick" && (
        <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
          <div>
            <label className="field-label">Add to phonebook</label>
            <div style={{ display: "flex", gap: 8, marginBottom: 8 }}>
              {phonebooks.length > 0 && (
                <button type="button" className={`btn ${pbMode === "existing" ? "btn-primary" : "btn-ghost"}`} style={{ flex: 1 }} onClick={() => setPbMode("existing")}>
                  Existing
                </button>
              )}
              <button type="button" className={`btn ${pbMode === "new" ? "btn-primary" : "btn-ghost"}`} style={{ flex: 1 }} onClick={() => setPbMode("new")}>
                Create new
              </button>
            </div>
            {pbMode === "existing" ? (
              <select className="select" value={pbId} onChange={(e) => setPbId(e.target.value)}>
                {phonebooks.map((pb) => <option key={pb.id} value={pb.id}>{pb.name} ({pb.count})</option>)}
              </select>
            ) : (
              <input className="input" placeholder="e.g. Mercedes Lucknow leads" value={newPbName} onChange={(e) => setNewPbName(e.target.value)}/>
            )}
          </div>

          <Field label="CSV file" hint='Must contain columns "name", "phone", optionally "email" and "company".'>
            <input
              ref={fileRef} className="input" type="file" accept=".csv,text/csv,text/plain"
              onChange={(e) => onFile(e.target.files?.[0])}
            />
          </Field>

          {csvText && (
            <div>
              <div style={{ fontSize: 11.5, color: "var(--ink-3)", marginBottom: 6 }}>Preview ({csvText.length.toLocaleString()} chars)</div>
              <pre style={{ background: "var(--surface-2)", padding: 10, borderRadius: 8, fontSize: 11, maxHeight: 100, overflow: "auto", margin: 0, fontFamily: "var(--font-mono)" }}>
                {csvText.split("\n").slice(0, 4).join("\n")}{csvText.split("\n").length > 4 ? "\n…" : ""}
              </pre>
            </div>
          )}

          <div style={{ display: "flex", gap: 8, justifyContent: "flex-end", marginTop: 6 }}>
            <Btn kind="ghost"   onClick={onClose} type="button">Cancel</Btn>
            <Btn kind="primary" onClick={submit}>Import</Btn>
          </div>
        </div>
      )}

      {step === "uploading" && (
        <div style={{ padding: "30px 0", textAlign: "center" }}>
          <div className="auth-boot-dot" style={{ width: 12, height: 12 }}/>
          <div style={{ marginTop: 14, color: "var(--ink-3)" }}>Importing contacts…</div>
        </div>
      )}

      {step === "done" && result && (
        <div style={{ textAlign: "center", padding: "20px 0" }}>
          <div style={{ color: "var(--ok)", margin: "0 auto 14px" }}><I.check size={32}/></div>
          <h3 style={{ margin: "0 0 14px", fontSize: 17, fontWeight: 600 }}>Import complete</h3>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 8, marginBottom: 18 }}>
            <Stat label="Imported"  value={result.inserted} color="var(--ok)"/>
            <Stat label="Duplicates" value={result.dupes}   color="var(--ink-3)"/>
            <Stat label="Invalid"    value={result.invalid} color="var(--err)"/>
          </div>
          <div style={{ display: "flex", gap: 8, justifyContent: "center" }}>
            <Btn kind="primary" onClick={onUploaded}>Done</Btn>
          </div>
        </div>
      )}
    </Modal>
  );
}

function Stat({ label, value, color }) {
  return (
    <div style={{ background: "var(--surface-2)", padding: 14, borderRadius: 10 }}>
      <div style={{ fontSize: 22, fontWeight: 600, color, letterSpacing: "-0.02em" }} className="tabular">{Number(value || 0).toLocaleString("en-IN")}</div>
      <div style={{ fontSize: 11.5, color: "var(--ink-3)", marginTop: 2 }}>{label}</div>
    </div>
  );
}

// ── Add contact manually ────────────────────────────────────────────────
function AddContactModal({ phonebooks, onClose, onAdded }) {
  const [form, setForm] = React.useState({
    name: "", phone: "", email: "", company: "",
    phonebook_id: phonebooks[0]?.id || "",
  });
  const [submitting, setSubmitting] = React.useState(false);
  const [err, setErr] = React.useState(null);

  const submit = async (e) => {
    e.preventDefault();
    setErr(null);
    if (!form.phone) return setErr("Phone number is required.");
    setSubmitting(true);
    const r = await VoaisAPI.post("/api/contacts", {
      ...form,
      phonebook_id: form.phonebook_id || null,
    });
    setSubmitting(false);
    if (r.ok) onAdded();
    else      setErr(r.data?.msg || "Failed to add contact.");
  };

  return (
    <Modal title="Add contact" 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="Name">
          <input className="input" autoFocus placeholder="Rohit Sharma" value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })}/>
        </Field>
        <Field label="Phone *" hint="Indian numbers OK without country code; we'll normalise to +91…">
          <input className="input" placeholder="9820145578" value={form.phone} onChange={(e) => setForm({ ...form, phone: e.target.value })}/>
        </Field>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
          <Field label="Email">
            <input className="input" type="email" placeholder="rohit@example.com" value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })}/>
          </Field>
          <Field label="Company">
            <input className="input" placeholder="Acme Inc" value={form.company} onChange={(e) => setForm({ ...form, company: e.target.value })}/>
          </Field>
        </div>
        {phonebooks.length > 0 && (
          <Field label="Add to phonebook (optional)">
            <select className="select" value={form.phonebook_id} onChange={(e) => setForm({ ...form, phonebook_id: e.target.value })}>
              <option value="">—</option>
              {phonebooks.map((pb) => <option key={pb.id} value={pb.id}>{pb.name}</option>)}
            </select>
          </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 contact"}
          </Btn>
        </div>
      </form>
    </Modal>
  );
}

window.ContactsScreen = ContactsScreen;
