// ============================================================================
// public/screens/whatsapp.jsx — WhatsApp Business (Phase 6C)
// ============================================================================

function WhatsAppScreen() {
  const [tab, setTab] = React.useState("templates"); // templates | conversations | broadcasts

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: "var(--gap-grid)" }}>
      <Tabs value={tab} onChange={setTab} options={[
        { value: "templates",     label: "Templates" },
        { value: "conversations", label: "Conversations" },
        { value: "broadcasts",    label: "Broadcasts" },
      ]}/>
      {tab === "templates" && <WaTemplatesTab/>}
      {tab === "conversations" && <WaConversationsTab/>}
      {tab === "broadcasts" && <WaBroadcastsTab/>}
    </div>
  );
}

// ── Templates ───────────────────────────────────────────────────────────
function WaTemplatesTab() {
  const [tpls, setTpls] = React.useState(null);
  const [showCreate, setShow] = React.useState(false);

  const load = async () => { const r = await VoaisAPI.get("/api/whatsapp/templates"); if (r.ok) setTpls(r.data.templates); };
  React.useEffect(() => { load(); }, []);

  const del = async (id) => { if (!confirm("Delete template?")) return; await VoaisAPI.del("/api/whatsapp/templates/" + id); load(); };

  if (tpls === null) return <DashboardSkeleton/>;

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: "var(--gap-grid)" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
        <Badge tone="blue" dot>{tpls.length} templates</Badge>
        <div style={{ flex: 1 }}/>
        <Btn kind="primary" size="sm" icon={<I.plus size={13}/>} onClick={() => setShow(true)}>New template</Btn>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(300px, 1fr))", gap: "var(--gap-grid)" }}>
        {tpls.map(t => (
          <Card key={t.id}>
            <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 8 }}>
              <I.template size={16} style={{ color: "var(--accent)" }}/>
              <span style={{ fontSize: 14, fontWeight: 600, flex: 1 }}>{t.name}</span>
              <Badge tone={t.status === "approved" ? "green" : t.status === "rejected" ? "red" : "yellow"}>{t.status}</Badge>
            </div>
            <div style={{ fontSize: 12, color: "var(--ink-3)", marginBottom: 8 }}>
              <Badge tone="gray">{t.category}</Badge> · {t.language} · {t.code}
            </div>
            <div style={{ padding: "10px 12px", background: "var(--surface-2)", borderRadius: 8, fontSize: 13, lineHeight: 1.6, whiteSpace: "pre-wrap" }}>
              {t.body?.slice(0, 200)}{t.body?.length > 200 ? "..." : ""}
            </div>
            <div style={{ display: "flex", gap: 8, marginTop: 10 }}>
              <span style={{ fontSize: 11, color: "var(--ink-3)", flex: 1 }}>Sent {t.sent_count || 0}x</span>
              <Btn kind="ghost" size="sm" onClick={() => del(t.id)}><I.trash size={12}/></Btn>
            </div>
          </Card>
        ))}
      </div>

      {tpls.length === 0 && <Card><Empty title="No templates" sub="Create your first WhatsApp template to start sending messages." icon={<I.template size={32}/>} action={<Btn kind="primary" onClick={() => setShow(true)}>Create template</Btn>}/></Card>}

      {showCreate && <CreateTemplateModal onClose={() => setShow(false)} onCreated={() => { setShow(false); load(); }}/>}
    </div>
  );
}

function CreateTemplateModal({ onClose, onCreated }) {
  const [f, setF] = React.useState({ name: "", category: "utility", language: "en_IN", body: "", footer: "" });
  const [sub, setSub] = React.useState(false);
  const submit = async () => { if (!f.name.trim() || !f.body.trim()) return; setSub(true); const r = await VoaisAPI.post("/api/whatsapp/templates", f); setSub(false); if (r.ok) onCreated(); else alert(r.data?.msg); };
  return (
    <Modal title="New WhatsApp template" onClose={onClose} width={520}>
      <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
        <Field label="Template name *"><input className="input" autoFocus value={f.name} onChange={e => setF({...f, name: e.target.value})} placeholder="e.g. test_drive_confirmation"/></Field>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
          <Field label="Category"><select className="select" value={f.category} onChange={e => setF({...f, category: e.target.value})}><option value="utility">Utility</option><option value="marketing">Marketing</option><option value="authentication">Authentication</option></select></Field>
          <Field label="Language"><select className="select" value={f.language} onChange={e => setF({...f, language: e.target.value})}><option value="en_IN">English (India)</option><option value="hi">Hindi</option><option value="en">English</option></select></Field>
        </div>
        <Field label="Body *" hint="Use {{1}}, {{2}} for variables"><textarea className="textarea" rows={5} value={f.body} onChange={e => setF({...f, body: e.target.value})} placeholder="Hello {{1}}! Your appointment is confirmed for {{2}}. Reply CONFIRM to confirm or CANCEL to cancel."/></Field>
        <Field label="Footer"><input className="input" value={f.footer} onChange={e => setF({...f, footer: e.target.value})} placeholder="Powered by VoAIs"/></Field>
        <div style={{ display: "flex", gap: 8, justifyContent: "flex-end" }}><Btn kind="ghost" onClick={onClose}>Cancel</Btn><Btn kind="primary" onClick={submit} disabled={sub}>{sub ? "Creating..." : "Create"}</Btn></div>
      </div>
    </Modal>
  );
}

// ── Conversations ───────────────────────────────────────────────────────
function WaConversationsTab() {
  const [threads, setThreads] = React.useState(null);
  const [active, setActive]   = React.useState(null);
  const [msgs, setMsgs]       = React.useState([]);
  const [reply, setReply]     = React.useState("");

  const load = async () => { const r = await VoaisAPI.get("/api/whatsapp/threads"); if (r.ok) setThreads(r.data.threads); };
  React.useEffect(() => { load(); }, []);

  const openThread = async (id) => {
    const r = await VoaisAPI.get("/api/whatsapp/threads/" + id);
    if (r.ok) { setActive(r.data.thread); setMsgs(r.data.messages); }
  };

  const sendMsg = async () => {
    if (!reply.trim() || !active) return;
    await VoaisAPI.post("/api/whatsapp/threads/" + active.id + "/send", { content: reply, type: "text" });
    setReply(""); openThread(active.id);
  };

  if (threads === null) return <DashboardSkeleton/>;

  return (
    <div style={{ display: "flex", gap: 0, height: "calc(100vh - 200px)", border: "1px solid var(--line)", borderRadius: 8, overflow: "hidden" }}>
      {/* Thread list */}
      <div style={{ width: 320, borderRight: "1px solid var(--line)", overflowY: "auto" }}>
        {threads.map(t => (
          <div key={t.id} onClick={() => openThread(t.id)} style={{
            padding: "12px 14px", cursor: "pointer", borderBottom: "1px solid var(--line)",
            background: active?.id === t.id ? "var(--accent-soft)" : "transparent",
          }}>
            <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
              <span style={{ fontSize: 13, fontWeight: t.unread_count > 0 ? 600 : 400, flex: 1 }}>{t.display_name || t.wa_number}</span>
              {t.unread_count > 0 && <span style={{ minWidth: 18, height: 18, borderRadius: 9, background: "var(--accent)", color: "#fff", fontSize: 10, fontWeight: 600, display: "grid", placeItems: "center" }}>{t.unread_count}</span>}
            </div>
            <div style={{ fontSize: 12, color: "var(--ink-3)", marginTop: 3, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{t.last_message_preview || "—"}</div>
          </div>
        ))}
        {threads.length === 0 && <div style={{ padding: 32, textAlign: "center", color: "var(--ink-3)", fontSize: 13 }}>No WhatsApp conversations yet.</div>}
      </div>

      {/* Chat panel */}
      <div style={{ flex: 1, display: "flex", flexDirection: "column" }}>
        {!active ? (
          <div style={{ flex: 1, display: "grid", placeItems: "center", color: "var(--ink-3)" }}>
            <div style={{ textAlign: "center" }}><I.whatsapp size={32} style={{ opacity: 0.3, marginBottom: 8 }}/><div style={{ fontSize: 13 }}>Select a conversation</div></div>
          </div>
        ) : (<>
          <div style={{ padding: "10px 16px", borderBottom: "1px solid var(--line)" }}>
            <div style={{ fontWeight: 600 }}>{active.display_name || active.wa_number}</div>
            <div style={{ fontSize: 12, color: "var(--ink-3)" }}>{active.wa_number} · {active.status}</div>
          </div>
          <div style={{ flex: 1, overflowY: "auto", padding: 12, display: "flex", flexDirection: "column", gap: 4 }}>
            {msgs.map((m, i) => (
              <div key={i} style={{
                padding: "8px 12px", borderRadius: 10, fontSize: 13, maxWidth: "75%",
                background: m.direction === "outbound" ? "var(--accent-soft)" : "var(--surface-2)",
                alignSelf: m.direction === "outbound" ? "flex-end" : "flex-start",
              }}>
                {m.content}
                <div style={{ fontSize: 10, color: "var(--ink-3)", marginTop: 2, textAlign: "right" }}>
                  {m.created_at ? new Date(m.created_at).toLocaleTimeString("en-IN", { hour: "2-digit", minute: "2-digit" }) : ""}
                </div>
              </div>
            ))}
          </div>
          <div style={{ padding: "10px 12px", borderTop: "1px solid var(--line)", display: "flex", gap: 8 }}>
            <input className="input" style={{ flex: 1 }} value={reply} onChange={e => setReply(e.target.value)}
              onKeyDown={e => { if (e.key === "Enter") sendMsg(); }} placeholder="Type a message..."/>
            <Btn kind="primary" icon={<I.send size={14}/>} onClick={sendMsg}>Send</Btn>
          </div>
        </>)}
      </div>
    </div>
  );
}

// ── Broadcasts ──────────────────────────────────────────────────────────
function WaBroadcastsTab() {
  const [bcs, setBcs] = React.useState(null);
  const [showCreate, setShow] = React.useState(false);

  const load = async () => { const r = await VoaisAPI.get("/api/whatsapp/broadcasts"); if (r.ok) setBcs(r.data.broadcasts); };
  React.useEffect(() => { load(); }, []);

  if (bcs === null) return <DashboardSkeleton/>;

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: "var(--gap-grid)" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
        <Badge tone="blue" dot>{bcs.length} broadcasts</Badge>
        <div style={{ flex: 1 }}/>
        <Btn kind="primary" size="sm" icon={<I.plus size={13}/>} onClick={() => setShow(true)}>New broadcast</Btn>
      </div>

      <Card padded={false}>
        <table className="data-table" style={{ width: "100%", fontSize: 13 }}>
          <thead><tr><th style={{ paddingLeft: 16 }}>Broadcast</th><th>Status</th><th>Sent</th><th>Delivered</th><th>Read</th><th>Failed</th><th>Created</th></tr></thead>
          <tbody>
            {bcs.map(b => (
              <tr key={b.id}>
                <td style={{ paddingLeft: 16 }}><div style={{ fontWeight: 500 }}>{b.name}</div><div style={{ fontSize: 11, color: "var(--ink-3)" }}>{b.code}</div></td>
                <td><Badge tone={b.status === "completed" ? "green" : b.status === "sending" ? "blue" : b.status === "failed" ? "red" : "gray"}>{b.status}</Badge></td>
                <td className="tabular">{b.sent}/{b.total}</td>
                <td className="tabular">{b.delivered}</td>
                <td className="tabular">{b.read}</td>
                <td className="tabular" style={{ color: b.failed > 0 ? "var(--err)" : undefined }}>{b.failed}</td>
                <td style={{ fontSize: 11, color: "var(--ink-3)" }}>{new Date(b.created_at).toLocaleDateString("en-IN", { day: "numeric", month: "short" })}</td>
              </tr>
            ))}
            {bcs.length === 0 && <tr><td colSpan={7} style={{ textAlign: "center", padding: 32, color: "var(--ink-3)" }}>No broadcasts yet.</td></tr>}
          </tbody>
        </table>
      </Card>

      {showCreate && (
        <Modal title="New broadcast" onClose={() => setShow(false)} width={460}>
          <CreateBroadcastForm onCreated={() => { setShow(false); load(); }}/>
        </Modal>
      )}
    </div>
  );
}

function CreateBroadcastForm({ onCreated }) {
  const [name, setName] = React.useState(""); const [sub, setSub] = React.useState(false);
  const submit = async () => { if (!name.trim()) return; setSub(true); const r = await VoaisAPI.post("/api/whatsapp/broadcasts", { name }); setSub(false); if (r.ok) onCreated(); };
  return (<div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
    <Field label="Broadcast name *"><input className="input" autoFocus value={name} onChange={e => setName(e.target.value)} placeholder="e.g. May promo — GLE owners"/></Field>
    <Btn kind="primary" onClick={submit} disabled={sub || !name.trim()}>{sub ? "Creating..." : "Create"}</Btn>
  </div>);
}

window.WhatsAppScreen = WhatsAppScreen;
