import { IItem, IShortcut, ShortcutType } from '@rpg-engine/shared';
import { useCallback, useEffect, useState } from 'react';
import { SHORTCUTS_STORAGE_KEY, defaultShortcut } from '../components/Spellbook/constants';

interface IUseShortcuts {
  itemContainer: { slots: Record<number, IItem | null | undefined>; };
}

export const useShortcuts = ({ itemContainer }: IUseShortcuts) => {
  const [shortcuts, setShortcuts] = useState<IShortcut[]>([]);

  useEffect(() => {
    const storedShortcuts = localStorage.getItem(SHORTCUTS_STORAGE_KEY);
    if (storedShortcuts) {
      setShortcuts(JSON.parse(storedShortcuts));
    }
  }, []);

  const setItemShortcut = useCallback((key: string, index: number): void => {
    const storedShortcuts = localStorage.getItem(SHORTCUTS_STORAGE_KEY);
    let updatedShortcuts = storedShortcuts ? JSON.parse(storedShortcuts) as IShortcut[] : [];

    let item: IItem | null = null;
    Object.keys(itemContainer.slots).forEach(slot => {
      const slotItem = itemContainer.slots[parseInt(slot)];
      if (slotItem && slotItem.key === key) {
        item = slotItem;
      }
    });

    if (!item) return;

    updatedShortcuts[index] = { type: ShortcutType.Item, payload: item };
    localStorage.setItem(SHORTCUTS_STORAGE_KEY, JSON.stringify(updatedShortcuts));
    setShortcuts(updatedShortcuts);
  }, [itemContainer]);

  const removeShortcut = useCallback((index: number): void => {
    const storedShortcuts = localStorage.getItem(SHORTCUTS_STORAGE_KEY);
    let updatedShortcuts = storedShortcuts ? JSON.parse(storedShortcuts) as IShortcut[] : [];

    if (updatedShortcuts[index]) {
      updatedShortcuts[index] = defaultShortcut;
      localStorage.setItem(SHORTCUTS_STORAGE_KEY, JSON.stringify(updatedShortcuts));
      setShortcuts(updatedShortcuts);
    }
  }, []);

  return { shortcuts, setItemShortcut, removeShortcut };
};
