// Groups & Channels screen: combined Source + Target groups with role filter tabs.
// Fetches both APIs in parallel, merges into unified list with role field.

const { useState } = React;

// ─── Source group form modal ─────────────────────────────────────────────
const SourceGroupModal = ({ open, onClose, onSaved, initial = {} }) => {
  const toast = useToast();
  const [form, setForm] = useState({
    name: "", platform_group_id: "", platform: "telegram",
    description: "", language: "vi", topics_enabled: false,
    topic_id: "", xoa_link: false,
    ...initial,
  });
  const [saving, setSaving] = useState(false);
  const set = (k, v) => setForm((f) => ({ ...f, [k]: v }));

  const handleSave = async () => {
    if (!form.name || !form.platform_group_id) {
      toast.error("Name and Group ID are required");
      return;
    }
    setSaving(true);
    try {
      await SourceGroupApi.save(form);
      toast.success(initial._id ? "Source group updated" : "Source group 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 Source Group" : "Add Source Group"}
      subtitle="Group that messages are forwarded FROM"
      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">Name</label>
        <input className="input" value={form.name} onChange={(e) => set("name", e.target.value)} />
      </div>
      <div className="field">
        <label className="field-label">Platform Group ID</label>
        <input className="input mono" value={form.platform_group_id} onChange={(e) => set("platform_group_id", e.target.value)} placeholder="-100123456789" />
      </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">Language</label>
        <select className="select" value={form.language} onChange={(e) => set("language", e.target.value)}>
          <option value="vi">Vietnamese</option>
          <option value="en">English</option>
        </select>
      </div>
      <div className="field">
        <label className="field-label">Description</label>
        <input className="input" value={form.description} onChange={(e) => set("description", e.target.value)} />
      </div>
      <div className="field">
        <label className="field-label" style={{ display: "flex", justifyContent: "space-between" }}>
          <span>Topics enabled</span>
          <input type="checkbox" checked={form.topics_enabled} onChange={(e) => set("topics_enabled", e.target.checked)} />
        </label>
      </div>
      {form.topics_enabled && (
        <div className="field">
          <label className="field-label">Topic ID</label>
          <input className="input mono" value={form.topic_id} onChange={(e) => set("topic_id", e.target.value)} />
        </div>
      )}
      <div className="field">
        <label className="field-label" style={{ display: "flex", justifyContent: "space-between" }}>
          <span>Remove links</span>
          <input type="checkbox" checked={form.xoa_link} onChange={(e) => set("xoa_link", e.target.checked)} />
        </label>
      </div>
    </Modal>
  );
};

// ─── Target group form modal ─────────────────────────────────────────────
const TargetGroupModal = ({ open, onClose, onSaved, initial = {} }) => {
  const toast = useToast();
  const [form, setForm] = useState({
    name: "", platform_group_id: "", platform: "telegram",
    description: "", language: "vi", topics_enabled: false,
    topic_id: "", replace_username: "", watermark_image: "",
    ...initial,
  });
  const [saving, setSaving] = useState(false);
  const set = (k, v) => setForm((f) => ({ ...f, [k]: v }));

  const handleSave = async () => {
    if (!form.name || !form.platform_group_id) {
      toast.error("Name and Group ID are required");
      return;
    }
    setSaving(true);
    try {
      await TargetGroupApi.save(form);
      toast.success(initial._id ? "Target group updated" : "Target group 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 Target Group" : "Add Target Group"}
      subtitle="Group that messages are forwarded TO"
      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">Name</label>
        <input className="input" value={form.name} onChange={(e) => set("name", e.target.value)} />
      </div>
      <div className="field">
        <label className="field-label">Platform Group ID</label>
        <input className="input mono" value={form.platform_group_id} onChange={(e) => set("platform_group_id", e.target.value)} placeholder="-100123456789" />
      </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">Language</label>
        <select className="select" value={form.language} onChange={(e) => set("language", e.target.value)}>
          <option value="vi">Vietnamese</option>
          <option value="en">English</option>
        </select>
      </div>
      <div className="field">
        <label className="field-label">Description</label>
        <input className="input" value={form.description} onChange={(e) => set("description", e.target.value)} />
      </div>
      <div className="field">
        <label className="field-label" style={{ display: "flex", justifyContent: "space-between" }}>
          <span>Topics enabled</span>
          <input type="checkbox" checked={form.topics_enabled} onChange={(e) => set("topics_enabled", e.target.checked)} />
        </label>
      </div>
      {form.topics_enabled && (
        <div className="field">
          <label className="field-label">Topic ID</label>
          <input className="input mono" value={form.topic_id} onChange={(e) => set("topic_id", e.target.value)} />
        </div>
      )}
      <div className="field">
        <label className="field-label">Replace username <span className="muted">(optional)</span></label>
        <input className="input" value={form.replace_username} onChange={(e) => set("replace_username", e.target.value)} placeholder="@newhandle" />
      </div>
      <div className="field">
        <label className="field-label">Watermark image URL <span className="muted">(optional)</span></label>
        <input className="input" value={form.watermark_image} onChange={(e) => set("watermark_image", e.target.value)} />
      </div>
    </Modal>
  );
};

// ─── Groups screen ───────────────────────────────────────────────────────
const GroupsScreen = () => {
  const toast = useToast();
  const confirm = useConfirm();
  const [roleFilter, setRoleFilter] = useState("all");
  const [showAddSource, setShowAddSource] = useState(false);
  const [showAddTarget, setShowAddTarget] = useState(false);
  const [editItem, setEditItem] = useState(null); // { role, data }
  const [tick, setTick] = useState(0);
  const refetch = () => setTick((t) => t + 1);

  const { data, loading, error } = useApi(async () => {
    const [sources, targets] = await Promise.all([
      SourceGroupApi.list(),
      TargetGroupApi.list(),
    ]);
    return [
      ...sources.map((s) => ({ ...s, _role: "source" })),
      ...targets.map((t) => ({ ...t, _role: "target" })),
    ];
  }, [tick]);

  const all = data || [];
  const sources = all.filter((g) => g._role === "source");
  const targets = all.filter((g) => g._role === "target");
  const filtered = roleFilter === "all" ? all : roleFilter === "source" ? sources : targets;

  const handleDelete = async (item) => {
    const ok = await confirm("Delete group", `Delete "${item.name}"? This cannot be undone.`);
    if (!ok) return;
    try {
      if (item._role === "source") await SourceGroupApi.delete(item._id);
      else await TargetGroupApi.delete(item._id);
      toast.success("Group deleted");
      refetch();
    } catch (e) {
      toast.error(e.message);
    }
  };

  if (error) return (
    <div className="page">
      <Empty icon={I.AlertTriangle} title="Failed to load groups" 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">Groups & Channels</h1>
          <div className="page-sub">All sources and targets across both platforms.</div>
        </div>
        <div style={{ display: "flex", gap: 8 }}>
          <button className="btn" onClick={() => setShowAddSource(true)}><I.Plus /> Add source</button>
          <button className="btn primary" onClick={() => setShowAddTarget(true)}><I.Plus /> Add target</button>
        </div>
      </div>

      <div className="kpi-row" style={{ gridTemplateColumns: "repeat(2, 1fr)" }}>
        <Kpi label="Total sources" value={sources.length} />
        <Kpi label="Total targets" value={targets.length} />
      </div>

      <div className="toolbar">
        <div className="chip-group">
          {[
            { id: "all", label: "All" },
            { id: "source", label: "Sources" },
            { id: "target", label: "Targets" },
          ].map((f) => (
            <button key={f.id} className={`chip ${roleFilter === f.id ? "active" : ""}`} onClick={() => setRoleFilter(f.id)}>
              {f.label}
            </button>
          ))}
        </div>
      </div>

      <div className="card flush">
        <div style={{ overflow: "auto" }}>
          <table className="table">
            <thead>
              <tr>
                <th>Name</th>
                <th>Group ID</th>
                <th>Platform</th>
                <th>Role</th>
                <th>Language</th>
                <th>Topics</th>
                <th style={{ width: 80 }}>Actions</th>
              </tr>
            </thead>
            <tbody>
              {loading ? (
                <SkeletonRows cols={7} rows={4} />
              ) : filtered.length === 0 ? (
                <tr>
                  <td colSpan={7}>
                    <Empty icon={I.MessagesSquare} title="No groups found" sub="Add a source or target group to get started." />
                  </td>
                </tr>
              ) : (
                filtered.map((g) => (
                  <tr key={`${g._role}-${g._id}`}>
                    <td style={{ fontWeight: 500 }}>{g.name}</td>
                    <td className="mono muted">{g.platform_group_id}</td>
                    <td><PlatformChip platform={g.platform} /></td>
                    <td>
                      {g._role === "source"
                        ? <span className="badge blue"><span className="dot"></span>Source</span>
                        : <span className="badge green"><span className="dot"></span>Target</span>
                      }
                    </td>
                    <td className="muted">{g.language || "—"}</td>
                    <td>
                      {g.topics_enabled
                        ? <span className="badge accent"><span className="dot"></span>Topics</span>
                        : <span className="muted">—</span>
                      }
                    </td>
                    <td>
                      <div style={{ display: "flex", gap: 4 }}>
                        <button className="btn ghost icon-only sm" onClick={() => setEditItem({ role: g._role, data: g })}><I.Edit size={12} /></button>
                        <button className="btn ghost icon-only sm" onClick={() => handleDelete(g)} style={{ color: "var(--red-fg)" }}><I.Trash size={12} /></button>
                      </div>
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      </div>

      <SourceGroupModal open={showAddSource} onClose={() => setShowAddSource(false)} onSaved={refetch} />
      <TargetGroupModal open={showAddTarget} onClose={() => setShowAddTarget(false)} onSaved={refetch} />

      {editItem?.role === "source" && (
        <SourceGroupModal open={true} onClose={() => setEditItem(null)} onSaved={() => { setEditItem(null); refetch(); }} initial={editItem.data} />
      )}
      {editItem?.role === "target" && (
        <TargetGroupModal open={true} onClose={() => setEditItem(null)} onSaved={() => { setEditItem(null); refetch(); }} initial={editItem.data} />
      )}
    </div>
  );
};

window.GroupsScreen = GroupsScreen;
