/* Routes.jsx — список маршрутів, live API. */

const { useState: useStateR, useEffect: useEffectR, useRef: useRefR } = React;

function slugifyRouteCode(name) {
  const map = {
    "а":"a","б":"b","в":"v","г":"g","ґ":"g","д":"d","е":"e","є":"ie",
    "ж":"zh","з":"z","и":"y","і":"i","ї":"yi","й":"y","к":"k","л":"l","м":"m",
    "н":"n","о":"o","п":"p","р":"r","с":"s","т":"t","у":"u","ф":"f","х":"kh",
    "ц":"ts","ч":"ch","ш":"sh","щ":"shch","ъ":"","ы":"y","ь":"","э":"e","ю":"iu","я":"ia",
  };
  let out = "";
  for (const ch of (name || "").toLowerCase()) out += map[ch] !== undefined ? map[ch] : ch;
  out = out.replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
  if (!out) out = "route";
  return out.slice(0, 30) + "-" + Math.floor(1000 + Math.random() * 9000);
}

function Routes({ onNav }) {
  const [routes, setRoutes] = useStateR([]);
  const [counts, setCounts] = useStateR({ all: 0, draft: 0, published: 0, archived: 0 });
  const [loading, setLoading] = useStateR(true);
  const [error, setError] = useStateR(null);
  const [search, setSearch] = useStateR("");
  const [filter, setFilter] = useStateR("all");
  const [drawerOpen, setDrawerOpen] = useStateR(false);
  const [saving, setSaving] = useStateR(false);
  const [createForm, setCreateForm] = useStateR({ name: "", notes: "" });
  const [createErrors, setCreateErrors] = useStateR({});

  const reload = async (opts = {}) => {
    setLoading(true);
    try {
      const res = await window.passengerApi.routes.list({
        search: opts.search ?? search,
        status: opts.filter ?? filter,
      });
      setRoutes(res.items || []);
      setCounts(res.counts || { all: 0, draft: 0, published: 0, archived: 0 });
      setError(null);
    } catch (e) {
      setError(e);
      window.showToast && window.showToast("Не вдалося завантажити маршрути: " + (e.message || ""), "bad");
    } finally {
      setLoading(false);
    }
  };

  useEffectR(() => { reload({ search, filter }); /* eslint-disable-next-line */ }, [search, filter]);
  window.passengerApi.usePolling(() => reload({ search, filter }), 30000, [search, filter]);

  const handlePauseResume = async (route) => {
    try {
      if (route.paused) {
        await window.passengerApi.routes.resume(route.id);
        window.showToast && window.showToast(`${route.code} відновлено`, "ok");
      } else {
        await window.passengerApi.routes.pause(route.id);
        window.showToast && window.showToast(
          `${route.code} призупинено`, "warn",
          async () => {
            try {
              await window.passengerApi.routes.resume(route.id);
              await reload();
              window.showToast && window.showToast(`${route.code} відновлено`, "ok");
            } catch (e) {
              window.showToast && window.showToast("Помилка відновлення: " + (e.message || ""), "bad");
            }
          }
        );
      }
      await reload();
    } catch (e) {
      window.showToast && window.showToast("Помилка: " + (e.message || ""), "bad");
    }
  };

  const handlePublish = async (route) => {
    try {
      await window.passengerApi.routes.publish(route.id);
      window.showToast && window.showToast(`${route.code} опубліковано`, "ok");
      await reload();
    } catch (e) {
      window.showToast && window.showToast("Помилка публікації: " + (e.message || ""), "bad");
    }
  };

  const handleDelete = async (route) => {
    try {
      await window.passengerApi.routes.remove(route.id);
      window.showToast && window.showToast(
        `Маршрут ${route.code} видалено`, "warn",
        async () => {
          try {
            await window.passengerApi.routes.restore(route.id);
            await reload();
            window.showToast && window.showToast(`${route.code} відновлено`, "ok");
          } catch (e) {
            window.showToast && window.showToast("Помилка відновлення: " + (e.message || ""), "bad");
          }
        }
      );
      await reload();
    } catch (e) {
      window.showToast && window.showToast("Помилка видалення: " + (e.message || ""), "bad");
    }
  };

  const handleCreate = async () => {
    setCreateErrors({});
    const name = (createForm.name || "").trim();
    if (!name) { setCreateErrors({ name: "Введіть назву" }); return; }
    setSaving(true);
    try {
      await window.passengerApi.routes.create({
        code: slugifyRouteCode(name),
        name,
        notes: createForm.notes || null,
        status: "draft",
      });
      window.showToast && window.showToast(`Маршрут «${name}» створено (чернетка)`, "info");
      setCreateForm({ name: "", notes: "" });
      setDrawerOpen(false);
      await reload();
    } catch (e) {
      if (e.errors) setCreateErrors(e.errors);
      else window.showToast && window.showToast("Помилка створення: " + (e.message || ""), "bad");
    } finally {
      setSaving(false);
    }
  };

  return (
    <>
      <Topbar
        title="Маршрути"
        subtitle={loading ? "Завантаження…" : `${counts.all} маршрутів`}
        actions={
          <button className="btn btn-primary btn-sm" onClick={() => setDrawerOpen(true)}>
            + Новий маршрут
          </button>
        }
      />

      <div className="page" style={{ animation: "fadeIn 0.2s ease" }}>

        {error && (
          <div className="alert-banner bad">
            <span>Помилка завантаження.</span>
            <button className="btn btn-sm btn-secondary" onClick={() => reload()}>Спробувати знову</button>
          </div>
        )}

        <div style={{ display: "flex", gap: 10, marginBottom: 16, alignItems: "center", flexWrap: "wrap" }}>
          <div style={{ position: "relative", flex: 1, maxWidth: 320 }}>
            <span style={{ position: "absolute", left: 10, top: "50%", transform: "translateY(-50%)", color: "var(--text-3)", fontSize: 14 }}>🔍</span>
            <input className="input" value={search} onChange={e => setSearch(e.target.value)}
              placeholder="Пошук маршруту…" style={{ paddingLeft: 32 }} />
          </div>
          <div className="segmented">
            {[
              { id: "all",       label: `Усі ${counts.all}` },
              { id: "published", label: `Активні ${counts.published}` },
              { id: "draft",     label: `Чернетки ${counts.draft}` },
            ].map(f => (
              <button key={f.id} className={filter === f.id ? "active" : ""} onClick={() => setFilter(f.id)}>
                {f.label}
              </button>
            ))}
          </div>
        </div>

        {loading ? (
          <div style={{ padding: 60, textAlign: "center", color: "var(--text-3)" }}>
            <span style={{ display: "inline-block", animation: "spin 1s linear infinite", marginRight: 6 }}>⟳</span>
            Завантаження…
          </div>
        ) : routes.length === 0 ? (
          <div style={{ padding: 60, textAlign: "center", color: "var(--text-3)" }}>
            <div style={{ fontSize: 32, marginBottom: 12 }}>🛤</div>
            <div style={{ fontSize: 15, fontWeight: 600, color: "var(--text-2)", marginBottom: 6 }}>
              {search ? `Нічого за «${search}»` : "Маршрутів немає"}
            </div>
            <div style={{ display: "flex", gap: 8, justifyContent: "center", marginTop: 12 }}>
              {search
                ? <button className="btn btn-secondary btn-sm" onClick={() => { setSearch(""); setFilter("all"); }}>Скинути фільтри</button>
                : <button className="btn btn-primary btn-sm" onClick={() => setDrawerOpen(true)}>+ Новий маршрут</button>
              }
            </div>
          </div>
        ) : (
          <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
            {routes.map(route => (
              <RouteCard key={route.id} route={route}
                onPauseResume={() => handlePauseResume(route)}
                onPublish={() => handlePublish(route)}
                onDelete={() => handleDelete(route)}
                onNav={onNav} />
            ))}
          </div>
        )}
      </div>

      <Drawer
        open={drawerOpen}
        onClose={() => { if (!saving) setDrawerOpen(false); }}
        title="Новий маршрут"
        width={420}
        footer={<>
          <button className="btn btn-secondary" disabled={saving} onClick={() => setDrawerOpen(false)}>Скасувати</button>
          <button className="btn btn-primary" disabled={saving} onClick={handleCreate}>
            {saving ? "Створюю…" : "Створити (чернетка)"}
          </button>
        </>}
      >
        <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
          <div>
            <label className="field-label">Назва маршруту *</label>
            <input className={"input" + (createErrors.name ? " error" : "")}
              value={createForm.name}
              onChange={e => { setCreateForm(f => ({ ...f, name: e.target.value })); setCreateErrors(er => ({ ...er, name: "" })); }}
              placeholder="напр. Хрещатик ↔ Сирець" autoFocus />
            {createErrors.name && <div className="field-error">{createErrors.name}</div>}
          </div>
          <div>
            <label className="field-label">Нотатки</label>
            <textarea className="input" rows={3}
              value={createForm.notes}
              onChange={e => setCreateForm(f => ({ ...f, notes: e.target.value }))}
              placeholder="Опціонально: початкові нотатки" style={{ resize: "vertical" }} />
          </div>
          <div style={{ fontSize: 12, color: "var(--text-3)" }}>
            Зупинки і призначення ТЗ — у конструкторі (буде в наступному паку).
            Код маршруту згенерується автоматично з назви.
          </div>
        </div>
      </Drawer>
    </>
  );
}

function RouteCard({ route, onPauseResume, onPublish, onDelete, onNav }) {
  const [hovered, setHovered] = useStateR(false);

  const statusBadge = route.paused
    ? <span className="badge badge-warn">⏸ Призупинено</span>
    : route.status === "published"
      ? <span className="badge badge-ok">● Активний</span>
      : <span className="badge badge-neutral">○ Чернетка</span>;

  return (
    <div
      className="card"
      onMouseEnter={() => setHovered(true)}
      onMouseLeave={() => setHovered(false)}
      style={{
        padding: "16px 18px",
        borderColor: route.problem_flag ? "var(--bad-border)" : hovered ? "var(--border-2)" : "var(--border)",
        background: route.problem_flag ? "var(--bad-bg)" : "var(--surface)",
        transition: "all 0.12s",
      }}
    >
      <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
        <div style={{
          width: 52, height: 52, borderRadius: 10,
          background: route.problem_flag ? "var(--bad)" : "var(--sb-bg)",
          display: "grid", placeItems: "center",
          color: "white", fontWeight: 700, fontSize: 12,
          flexShrink: 0, padding: "0 6px", textAlign: "center",
        }}>
          {route.code.length > 8 ? route.code.slice(0, 8) : route.code}
        </div>

        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 4 }}>
            <span style={{ fontWeight: 600, fontSize: 15 }}>{route.name}</span>
            {statusBadge}
            {route.problem_flag && <span className="badge badge-bad">⚠ Проблема</span>}
          </div>
          <div style={{ display: "flex", gap: 16, fontSize: 12.5, color: "var(--text-3)", flexWrap: "wrap" }}>
            <span>📍 {route.stops_count || 0} зупинок</span>
            <span style={{ fontFamily: "monospace" }}>v{route.version}</span>
            <span style={{ fontFamily: "monospace" }}>{route.code}</span>
          </div>
        </div>

        <div style={{ display: "flex", gap: 6, opacity: hovered ? 1 : 0.0, transition: "opacity 0.12s" }}>
          {route.status === "draft" && !route.paused && (
            <button className="btn btn-secondary btn-sm" onClick={onPublish}>
              Опублікувати
            </button>
          )}
          {route.status === "published" && (
            <button
              className={"btn btn-sm " + (route.paused ? "btn-primary" : "btn-ghost")}
              style={!route.paused ? { color: "var(--warn)", borderColor: "var(--warn-border)" } : {}}
              onClick={onPauseResume}>
              {route.paused ? "▶ Відновити" : "⏸ Призупинити"}
            </button>
          )}
          <button className="btn btn-ghost btn-sm" style={{ color: "var(--bad)" }} onClick={onDelete}>
            Видалити
          </button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Routes });
