import { useCallback } from 'react';
import { useLayerStore } from '../store/layer-store.mjs';
import { useEditorStore } from '../store/editor-store.mjs';
import { canLayerAcceptChildren } from '../store/layer-utils.mjs';

const useDropValidation = (activeLayerId, isLayerDescendantOf, newComponentType) => {
  const findLayerById = useLayerStore((state) => state.findLayerById);
  const componentRegistry = useEditorStore((state) => state.registry);
  const canDropOnLayer = useCallback((layerId) => {
    if (!layerId) return false;
    const targetLayer = findLayerById(layerId);
    if (!targetLayer) return false;
    if (!activeLayerId && !newComponentType) {
      return canLayerAcceptChildren(targetLayer, componentRegistry);
    }
    if (newComponentType) {
      const componentDef = componentRegistry[newComponentType];
      if (componentDef?.childOf && !componentDef.childOf.includes(targetLayer.type)) {
        return false;
      }
      return canLayerAcceptChildren(targetLayer, componentRegistry);
    }
    if (activeLayerId) {
      if (isLayerDescendantOf(layerId, activeLayerId)) {
        return false;
      }
      const draggedLayer = findLayerById(activeLayerId);
      if (!draggedLayer) {
        return canLayerAcceptChildren(targetLayer, componentRegistry);
      }
      const draggedDef = componentRegistry[draggedLayer.type];
      if (draggedDef?.childOf && !draggedDef.childOf.includes(targetLayer.type)) {
        return false;
      }
    }
    return canLayerAcceptChildren(targetLayer, componentRegistry);
  }, [activeLayerId, newComponentType, isLayerDescendantOf, findLayerById, componentRegistry]);
  return { canDropOnLayer };
};

export { useDropValidation };
