// Bot management screen: list with filters + Add Bot modal.
// Uses real BotApi — no mock data.

const { useState, useCallback } = React;

// ─── Add/Edit Bot modal form ─────────────────────────────────────────────
const BotFormModal = ({ open, onClose, onSaved, initial = {} }) => {
  const toast = useToast();
  const [form, setForm] = useState({
    name: "", phone: "", platform: "telegram",
    api_id: "", api_hash: "", proxy: "", ai_enabled: false,
    ...initial,
  });
  const [saving, setSaving] = useState(false);

  const set = (k, v) => setForm((f) => ({ ...f, [k]: v }));

  const handleSave = async () => {
    if (!form.name || !form.phone || !form.api_id || !form.api_hash) {
      toast.error("Name, phone, API ID and API Hash are required");
      return;
    }
    setSaving(true);
    try {
      const payload = {
        ...form,
        platformConfig: { apiId: form.api_id, apiHash: form.api_hash },
      };
      await BotApi.save(payload);
      toast.success(initial._id ? "Bot updated" : "Bot added");
      onSaved();
      onClose();
    } catch (e) {
      toast.error(e.message);
    } finally {
      setSaving(false);
    }
  };

  if (!open) return null;
  return (
    <Modal
      open={open}
      onClose={onClose}
      title={initial._id ? "Edit Bot" : "Add Bot"}
      subtitle="Telegram bot credentials"
      footer={
        <>
          <button className="btn ghost" onClick={onClose}>Cancel</button>
          <button className="btn primary" onClick={handleSave} disabled={saving}>
            {saving ? "Saving…" : "Save"}
          </button>
        </>
      }
    >
      <div className="field">
        <label className="field-label">Display name</label>
        <input className="input" value={form.name} onChange={(e) => set("name", e.target.value)} placeholder="e.g. Bot #1" />
      </div>
      <div className="field">
        <label className="field-label">Phone number</label>
        <input className="input mono" value={form.phone} onChange={(e) => set("phone", e.target.value)} placeholder="+84901234567" />
      </div>
      <div className="field">
        <label className="field-label">Platform</label>
        <select className="select" value={form.platform} onChange={(e) => set("platform", e.target.value)}>
          <option value="telegram">Telegram</option>
          <option value="zalo">Zalo</option>
        </select>
      </div>
      <div className="field">
        <label className="field-label">API ID</label>
        <input className="input mono" value={form.api_id} onChange={(e) => set("api_id", e.target.value)} placeholder="12345678" />
      </div>
      <div className="field">
        <label className="field-label">API Hash</label>
        <input className="input mono" value={form.api_hash} onChange={(e) => set("api_hash", e.target.value)} placeholder="abc123…" />
      </div>
      <div className="field">
        <label className="field-label">Proxy <span className="muted">(optional — ip:port:user:pass)</span></label>
        <input className="input mono" value={form.proxy} onChange={(e) => set("proxy", e.target.value)} placeholder="127.0.0.1:1080:user:pass" />
      </div>
    </Modal>
  );
};

// ─── Bot list screen ──────────────────────────────────────────────────────
const BotsList = ({ onOpenBot }) => {
  const toast = useToast();
  const confirm = useConfirm();
  const [platform, setPlatform] = useState("all");
  const [statusFilter, setStatusFilter] = useState("all");
  const [showAdd, setShowAdd] = useState(false);
  const [editBot, setEditBot] = useState(null);
  const { data: bots, loading, error, refetch } = useApi(BotApi.list, []);

  const filtered = (bots || []).filter((b) =>
    (platform === "all" || b.platform === platform) &&
    (statusFilter === "all" || b.status === statusFilter)
  );

  const handleAction = async (action, bot) => {
    try {
      if (action === "delete") {
        const ok = await confirm("Delete bot", `Delete "${bot.name}"? This cannot be undone.`);
        if (!ok) return;
        await BotApi.delete(bot._id);
        toast.success("Bot deleted");
      } else if (action === "start") {
        await BotApi.start(bot._id);
        toast.success("Bot started");
      } else if (action === "stop") {
        await BotApi.stop(bot._id);
        toast.success("Bot stopped");
      } else if (action === "restart") {
        await BotApi.restart(bot._id);
        toast.success("Bot restarted");
      }
      refetch();
    } catch (e) {
      toast.error(e.message);
    }
  };

  const statusOptions = [
    { id: "all", label: "All" },
    { id: "active", label: "Active" },
    { id: "paused", label: "Paused" },
    { id: "error", label: "Error" },
    { id: "auth_required", label: "Auth Required" },
  ];

  if (error) return (
    <div className="page">
      <Empty icon={I.AlertTriangle} title="Failed to load bots" sub={error} action={<button className="btn" onClick={refetch}><I.Refresh /> Retry</button>} />
    </div>
  );

  return (
    <div className="page">
      <div className="page-head">
        <div>
          <h1 className="page-title">Bots</h1>
          <div className="page-sub">
            {loading ? "Loading…" : `${filtered.length} bots · ${filtered.filter((b) => b.status === "active").length} active`}
          </div>
        </div>
        <div style={{ display: "flex", gap: 8 }}>
          <button className="btn" onClick={refetch}><I.Refresh /> Refresh</button>
          <button className="btn primary" onClick={() => setShowAdd(true)}><I.Plus /> Add bot</button>
        </div>
      </div>

      <div className="toolbar">
        <PlatformFilter value={platform} onChange={setPlatform} />
        <div className="chip-group">
          {statusOptions.map((s) => (
            <button key={s.id} className={`chip ${statusFilter === s.id ? "active" : ""}`} onClick={() => setStatusFilter(s.id)}>
              {s.label}
            </button>
          ))}
        </div>
      </div>

      <div className="card flush">
        <div style={{ overflow: "auto" }}>
          <table className="table">
            <thead>
              <tr>
                <th>Bot</th>
                <th>Platform</th>
                <th>Status</th>
                <th className="num">Processed</th>
                <th className="num">Forwarded</th>
                <th>Last active</th>
                <th>Proxy</th>
                <th style={{ width: 120 }}>Actions</th>
              </tr>
            </thead>
            <tbody>
              {loading ? (
                <SkeletonRows cols={8} rows={5} />
              ) : filtered.length === 0 ? (
                <tr>
                  <td colSpan={8}>
                    <Empty icon={I.Bot} title="No bots found" sub="Add a bot to get started." />
                  </td>
                </tr>
              ) : (
                filtered.map((b) => (
                  <tr key={b._id} style={{ cursor: "pointer" }} onClick={() => onOpenBot?.(b._id, b.name)}>
                    <td>
                      <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                        <Avatar name={b.name} />
                        <div>
                          <div style={{ fontWeight: 500 }}>{b.name}</div>
                          <div className="mono muted" style={{ fontSize: 11 }}>{b.phone}</div>
                        </div>
                      </div>
                    </td>
                    <td><PlatformChip platform={b.platform} /></td>
                    <td><StatusBadge status={b.status} /></td>
                    <td className="num tnum">{(b.messages_processed || 0).toLocaleString()}</td>
                    <td className="num tnum">{(b.messages_forwarded || 0).toLocaleString()}</td>
                    <td className="muted">{relativeTime(b.last_active)}</td>
                    <td className="mono muted">{b.proxy || "—"}</td>
                    <td onClick={(e) => e.stopPropagation()}>
                      <div style={{ display: "flex", gap: 4 }}>
                        <button className="btn ghost icon-only sm" title="Edit" onClick={() => setEditBot(b)}><I.Edit size={12} /></button>
                        <button className="btn ghost icon-only sm" title="Restart" onClick={() => handleAction("restart", b)}><I.Refresh size={12} /></button>
                        <button className="btn ghost icon-only sm" title="Delete" onClick={() => handleAction("delete", b)} style={{ color: "var(--red-fg)" }}><I.Trash size={12} /></button>
                      </div>
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      </div>

      <BotFormModal open={showAdd} onClose={() => setShowAdd(false)} onSaved={refetch} />
      {editBot && (
        <BotFormModal
          open={!!editBot}
          onClose={() => setEditBot(null)}
          onSaved={() => { setEditBot(null); refetch(); }}
          initial={editBot}
        />
      )}
    </div>
  );
};

window.BotsList = BotsList;
