import { useCallback, useEffect, useState } from "react";
import { useI18n } from "../../i18n/I18nContext";
import { useRepos } from "../../data/DataContext";
import type { Workspace } from "../../domain/types";
import { AppIcon } from "../ui/AppIcons";

/** 頂欄 Workspace 切換（growth-loop P1） */
export function WorkspaceSwitcher() {
  const { t } = useI18n();
  const repos = useRepos();
  const [list, setList] = useState<Workspace[]>([]);
  const [currentId, setCurrentId] = useState("");
  const [busy, setBusy] = useState(false);

  const load = useCallback(async () => {
    try {
      const res = await repos.growth.listWorkspaces();
      setList(res.list);
      setCurrentId(res.current_workspace_id || res.list[0]?.id || "");
    } catch {
      /* ignore until auth ready */
    }
  }, [repos.growth]);

  useEffect(() => {
    void load();
  }, [load]);

  if (list.length === 0) return null;

  return (
    <label className="hb-ws-switch" title={t("workspace.label")}>
      <span className="hb-ws-switch__ico" aria-hidden>
        <AppIcon name="brands" size={16} />
      </span>
      <span className="hb-ws-switch__label">{t("workspace.label")}</span>
      <select
        className="hb-ws-switch__select"
        aria-label={t("workspace.label")}
        value={currentId}
        disabled={busy}
        onChange={(e) => {
          const id = e.target.value;
          if (id === "__new__") {
            const name = window.prompt(t("workspace.newPrompt"));
            if (!name?.trim()) return;
            setBusy(true);
            void repos.growth
              .createWorkspace(name.trim())
              .then((w) => repos.growth.switchWorkspace(w.id))
              .then((res) => {
                setList(res.list);
                setCurrentId(res.current_workspace_id);
              })
              .catch(() => undefined)
              .finally(() => setBusy(false));
            return;
          }
          if (id === currentId) return;
          setBusy(true);
          void repos.growth
            .switchWorkspace(id)
            .then((res) => {
              setList(res.list);
              setCurrentId(res.current_workspace_id);
            })
            .catch(() => undefined)
            .finally(() => setBusy(false));
        }}
      >
        {list.map((w) => (
          <option key={w.id} value={w.id}>
            {w.name}
            {w.is_default ? ` · ${t("workspace.default")}` : ""}
          </option>
        ))}
        <option value="__new__">{t("workspace.new")}</option>
      </select>
    </label>
  );
}
