import { useMemo } from 'react';
import type { DragEvent } from 'react';
import type { Identifier } from '../types/identifiers';

type FolderDropHandler = (
  event: DragEvent<HTMLElement>,
  folderId: Identifier,
) => void | Promise<void>;

interface FolderClickHandlers {
  onSelect: (folderId: Identifier | null) => void;
  onDrop: FolderDropHandler;
  onDragOver: (event: DragEvent<HTMLElement>, folderId: Identifier) => void;
  onDragLeave: (event: DragEvent<HTMLElement>) => void;
}


interface UseSidebarPropsArgs {
  folderClickHandlers: FolderClickHandlers;
  handleFolderDelete: (folderId: Identifier) => void | Promise<void>;
  handleFolderRename: (folderId: Identifier, name: string) => void | Promise<void>;
  selectedFolder: Identifier | null;
  handleFolderDragStart: (event: DragEvent<HTMLElement>, folderId: Identifier) => void;
  handleFolderDragEnd: (event: DragEvent<HTMLElement>) => void;
  draggedFolderId: Identifier | null;
  handlePromptCreateFolder?: (parentId?: Identifier | null) => void;
  creatingFolder: boolean;
}

interface SidebarHookResult {
  onSelect: FolderClickHandlers['onSelect'];
  onDrop: FolderClickHandlers['onDrop'];
  onDragOver: FolderClickHandlers['onDragOver'];
  onDragLeave: FolderClickHandlers['onDragLeave'];
  onDeleteFolder: UseSidebarPropsArgs['handleFolderDelete'];
  onRenameFolder: UseSidebarPropsArgs['handleFolderRename'];
  selectedFolder: Identifier | null;
  onFolderDragStart: UseSidebarPropsArgs['handleFolderDragStart'];
  onFolderDragEnd: UseSidebarPropsArgs['handleFolderDragEnd'];
  draggedFolderId: Identifier | null;
  onCreateFolder: UseSidebarPropsArgs['handlePromptCreateFolder'];
  creatingFolder: boolean;
}

const useSidebarProps = (args: UseSidebarPropsArgs): SidebarHookResult =>
  useMemo(
    () => ({
      onSelect: args.folderClickHandlers.onSelect,
      onDrop: args.folderClickHandlers.onDrop,
      onDragOver: args.folderClickHandlers.onDragOver,
      onDragLeave: args.folderClickHandlers.onDragLeave,
      onDeleteFolder: args.handleFolderDelete,
      onRenameFolder: args.handleFolderRename,
      selectedFolder: args.selectedFolder,
      onFolderDragStart: args.handleFolderDragStart,
      onFolderDragEnd: args.handleFolderDragEnd,
      draggedFolderId: args.draggedFolderId,
      onCreateFolder: (parentId) => args.handlePromptCreateFolder?.(parentId),
      creatingFolder: args.creatingFolder,
    }),
    [args],
  );

export default useSidebarProps;
