"use client";

import { useCallback, useEffect } from "react";
import { MoveEmbedPickerDialog } from "@/components/documents/move-embed-picker-dialog";
import { useMoveEmbedPickerStore } from "@/store/move-embed-picker";

export function MoveEmbedPickerHost() {
  const open = useMoveEmbedPickerStore((s) => s.open);
  const workspaceId = useMoveEmbedPickerStore((s) => s.workspaceId);
  const defaultMode = useMoveEmbedPickerStore((s) => s.defaultMode);
  const modes = useMoveEmbedPickerStore((s) => s.modes);
  const allowRoot = useMoveEmbedPickerStore((s) => s.allowRoot);
  const excludeIds = useMoveEmbedPickerStore((s) => s.excludeIds);
  const onPick = useMoveEmbedPickerStore((s) => s.onPick);
  const setWorkspaceId = useMoveEmbedPickerStore((s) => s.setWorkspaceId);
  const close = useMoveEmbedPickerStore((s) => s.close);

  useEffect(() => {
    if (!open) return;
    if (workspaceId) return;
    let cancelled = false;

    const run = async () => {
      try {
        const res = await fetch("/api/sidebar");
        if (!res.ok) return;
        const json = (await res.json().catch(() => null)) as { activeWorkspaceId?: string } | null;
        const nextId = typeof json?.activeWorkspaceId === "string" ? json.activeWorkspaceId : null;
        if (!cancelled) {
          setWorkspaceId(nextId);
        }
      } catch {
        // ignore
      }
    };

    void run();

    return () => {
      cancelled = true;
    };
  }, [open, setWorkspaceId, workspaceId]);

  const handlePick = useCallback(
    async (mode: "move" | "embed", targetId: string | null) => {
      if (onPick) {
        await onPick(mode, targetId);
      }
      close();
    },
    [close, onPick],
  );

  return (
    <MoveEmbedPickerDialog
      open={open}
      onOpenChange={(next) => {
        if (!next) {
          close();
        }
      }}
      workspaceId={workspaceId}
      defaultMode={defaultMode}
      modes={modes}
      allowRoot={allowRoot}
      excludeIds={excludeIds}
      onPick={handlePick}
    />
  );
}
