import { ref, computed, watch, nextTick, type Ref } from "vue";
import { useVueFlow } from "@vue-flow/core";

// 下方面板数据结构
export interface NodePanelData {
  content?: string;
  selectValue?: string;
  imgUrl?: string;
  videoUrl?: string;
}

// 悬浮面板与节点边缘的固定间距
const PANEL_GAP = 12;

/**
 * 面板状态：panelForm 双向同步、panelType 显示控制、面板屏幕定位
 */
export function usePanelState(
  selectedNode: Ref<any>,
  selectedNodeId: Ref<string | null>,
) {
  const { viewport } = useVueFlow();

  // ============ 面板类型 ============
  type PanelType = "editor" | "panel2" | null;
  const panelType = ref<PanelType>(null);
  const topPanelIndex = ref(0);

  // showTopBar: 上方面板是否显示（选中 + 已有文件）。裁剪时也显示（切换为裁剪工具条区块）
  const showTopBar = computed(() => {
    const node = selectedNode.value;
    return !!(node && node.data?.url);
  });

  // ============ 下方面板数据 ============
  const panelForm = ref<NodePanelData>({
    content: "",
    selectValue: "",
    imgUrl: "",
    videoUrl: "",
  });

  // 选中节点变化时：同步下方面板数据 + 控制面板显示
  watch(
    selectedNodeId,
    (id) => {
      const node = selectedNode.value;
      const p = node?.data?.panel;
      panelForm.value = {
        content: p?.content ?? "",
        selectValue: p?.selectValue ?? "",
        imgUrl: p?.imgUrl ?? "",
        videoUrl: p?.videoUrl ?? "",
      };

      if (id) {
        nextTick(() => {
          const node = selectedNode.value;
          if (node) {
            panelType.value = node.data?.url ? null : "editor";
          }
        });
      } else {
        panelType.value = null;
      }
    },
    { immediate: true },
  );

  // 节点被删除时兜底：selectedNode 变 null 则取消选中
  watch(selectedNode, (node) => {
    if (!node && selectedNodeId.value) {
      selectedNodeId.value = null;
    }
  });

  // 下方面板任一字段变化时：整体写回当前节点 data.panel
  watch(
    panelForm,
    (val) => {
      const node = selectedNode.value;
      if (!node) return;
      const cur = node.data?.panel;
      if (
        cur?.content === val.content &&
        cur?.selectValue === val.selectValue &&
        cur?.imgUrl === val.imgUrl &&
        cur?.videoUrl === val.videoUrl
      )
        return;
      node.data = { ...(node.data ?? {}), panel: { ...val } };
    },
    { deep: true },
  );

  // ============ 面板屏幕定位 ============
  // 上方面板：底部贴在「节点顶边 - 固定间距」处
  const floatingPanelStyleTop = computed(() => {
    const node = selectedNode.value;
    if (!node) return {};
    const { x: offsetX, y: offsetY, zoom } = viewport.value;
    const leftScreen = node.position.x * zoom + offsetX;
    const topScreen = node.position.y * zoom + offsetY;
    const widthScreen = (node.dimensions?.width ?? 0) * zoom;
    return {
      top: topScreen - PANEL_GAP + "px",
      left: leftScreen + widthScreen / 2 + "px",
      transform: "translate(-50%, -100%)",
    };
  });

  // 下方面板：顶部贴在「节点底边 + 固定间距」处
  const floatingPanelStyleBottom = computed(() => {
    const node = selectedNode.value;
    if (!node) return {};
    const { x: offsetX, y: offsetY, zoom } = viewport.value;
    const leftScreen = node.position.x * zoom + offsetX;
    const topScreen = node.position.y * zoom + offsetY;
    const widthScreen = (node.dimensions?.width ?? 0) * zoom;
    const heightScreen = (node.dimensions?.height ?? 0) * zoom;
    return {
      top: topScreen + heightScreen + PANEL_GAP + "px",
      left: leftScreen + widthScreen / 2 + "px",
      transform: "translate(-50%, 0)",
    };
  });

  return {
    panelType,
    topPanelIndex,
    showTopBar,
    panelForm,
    floatingPanelStyleTop,
    floatingPanelStyleBottom,
  };
}
