import { useEffect, useState } from "react";
import { listProjectFolders } from "../chats/project-api.js";
import { filterProjectFolders, projectListErrorMessage, projectOperationError } from "../chats/project-picker.js";
import { useI18n } from "../../shared/I18nProvider.jsx";
import { useExitTransition } from "../../app/useExitTransition.js";
import { CloseIcon, FolderIcon } from "../../shared/ActionIcons.jsx";

export function WorkspaceAttachPicker({ open, onClose, onAttach, onRegisterProject }) {
  const { t } = useI18n();
  const [projects, setProjects] = useState([]);
  const [search, setSearch] = useState("");
  const [pending, setPending] = useState("");
  const [error, setError] = useState("");
  const motion = useExitTransition(onClose, 220);

  useEffect(() => {
    if (!open) return;
    let active = true;
    setError("");
    listProjectFolders().then((result) => {
      if (active) setProjects(result.projects ?? []);
    }).catch((loadError) => {
      if (active) setError(projectListErrorMessage(loadError));
    });
    return () => { active = false; };
  }, [open]);

  if (!open) return null;

  async function select(project) {
    setPending(project.name);
    setError("");
    try {
      const selectedWorkspaceId = project.workspaceId
        ? project.workspaceId
        : await onRegisterProject(project.name);
      if (!selectedWorkspaceId) return;
      await onAttach(selectedWorkspaceId);
      motion.startExit();
    } catch (selectError) {
      setError(projectOperationError(selectError));
    } finally {
      setPending("");
    }
  }

  const visibleProjects = filterProjectFolders(projects, search);
  return <div className={`workspace-attach-backdrop${motion.exiting ? " workspace-attach-backdrop--exit" : ""}`} role="presentation" onPointerDown={(event) => { if (event.target === event.currentTarget) motion.startExit(); }}>
    <section className={`workspace-attach-sheet${motion.exiting ? " workspace-attach-sheet--exit" : ""}`} role="dialog" aria-modal="true" aria-labelledby="workspace-attach-title">
      <div className="workspace-attach-handle" aria-hidden="true"></div>
      <header><h2 id="workspace-attach-title">{t("conversation.selectProject")}</h2><button type="button" onClick={motion.startExit} aria-label={t("newChat.back")}><CloseIcon /></button></header>
      <input className="project-search" value={search} onChange={(event) => setSearch(event.target.value)} placeholder={t("newChat.search")} aria-label={t("newChat.search")} autoFocus />
      <div className="workspace-attach-list">{visibleProjects.map((project) => <button type="button" key={project.name} disabled={Boolean(pending)} onClick={() => select(project)}>
        <FolderIcon className="project-picker-icon" />
        <span>{project.name}</span>{pending === project.name && <span aria-label={t("newChat.starting")}>…</span>}
      </button>)}</div>
      {projects.length === 0 && !error && <p>{t("newChat.none")}</p>}
      {error && <p className="thread-state error" role="alert">{error}</p>}
    </section>
  </div>;
}
