'use client';

import { useCallback } from 'react';
import { useCanvasStore } from '@lib/store/canvasStore';

export function useCanvasSelection() {
  const selectedNodeIds = useCanvasStore((state) => state.selectedNodeIds);
  const setSelectedNodeIds = useCanvasStore((state) => state.setSelectedNodeIds);
  const selectedGroupId = useCanvasStore((state) => state.selectedGroupId);
  const setSelectedGroupId = useCanvasStore((state) => state.setSelectedGroupId);

  const selectNode = useCallback((nodeId: string, multiSelect = false) => {
    if (multiSelect) {
      setSelectedNodeIds((prev) =>
        prev.includes(nodeId)
          ? prev.filter((id) => id !== nodeId)
          : [...prev, nodeId]
      );
    } else {
      setSelectedNodeIds([nodeId]);
      setSelectedGroupId(null);
    }
  }, [setSelectedNodeIds, setSelectedGroupId]);

  const selectGroup = useCallback((groupId: string | null) => {
    setSelectedGroupId(groupId);
    if (groupId) {
      setSelectedNodeIds([]);
    }
  }, [setSelectedGroupId, setSelectedNodeIds]);

  const clearSelection = useCallback(() => {
    setSelectedNodeIds([]);
    setSelectedGroupId(null);
  }, [setSelectedNodeIds, setSelectedGroupId]);

  const selectAll = useCallback(() => {
    const nodes = useCanvasStore.getState().nodes;
    setSelectedNodeIds(nodes.map((n) => n.id));
  }, [setSelectedNodeIds]);

  return {
    selectedNodeIds,
    selectedGroupId,
    selectNode,
    selectGroup,
    clearSelection,
    selectAll,
  };
}
