import {
  getItemTextureKeyPath,
  IItem,
  IItemContainer,
  IRawSpell,
  IShortcut,
  ShortcutType,
} from '@rpg-engine/shared';
import React, { useCallback, useEffect, useRef } from 'react';
import styled from 'styled-components';
import { uiColors } from '../../constants/uiColors';
import { countItemFromInventory } from '../../libs/itemCounter';
import { SpriteFromAtlas } from '../shared/SpriteFromAtlas';
import { SingleShortcut } from './SingleShortcut';
import { useShortcutCooldown } from './useShortcutCooldown';

export type ShortcutsProps = {
  shortcuts: IShortcut[];
  onShortcutCast: (index: number) => void;
  mana: number;
  isBlockedCastingByKeyboard?: boolean;
  inventory?: IItemContainer | null;
  atlasJSON: any;
  atlasIMG: any;
  spellCooldowns?: Record<string, number>;
};

export const Shortcuts: React.FC<ShortcutsProps> = ({
  shortcuts,
  onShortcutCast,
  mana,
  isBlockedCastingByKeyboard = false,
  atlasJSON,
  atlasIMG,
  inventory,
  spellCooldowns,
}) => {
  const shortcutsRefs = useRef<HTMLButtonElement[]>([]);

  const { handleShortcutCast, shortcutCooldown } = useShortcutCooldown(
    onShortcutCast
  );

  const handleKeyDown = useCallback(
    (e: KeyboardEvent) => {
      if (isBlockedCastingByKeyboard) return;

      const shortcutIndex = Number(e.key) - 1;
      if (shortcutIndex >= 0 && shortcutIndex <= 11) {
        handleShortcutCast(shortcutIndex);
        shortcutsRefs.current[shortcutIndex]?.classList.add('active');
        const timeoutId = setTimeout(() => {
          shortcutsRefs.current[shortcutIndex]?.classList.remove('active');
        }, 150);
        // Store timeoutId for later cleanup
        timeoutIds.current.push((timeoutId as unknown) as number);
      }
    },
    [isBlockedCastingByKeyboard, handleShortcutCast]
  );

  // Initialize a ref to store the timeout ids
  const timeoutIds = useRef<number[]>([]);

  useEffect(() => {
    window.addEventListener('keydown', handleKeyDown);

    return () => {
      window.removeEventListener('keydown', handleKeyDown);
      // Clear all timeouts when the component unmounts
      timeoutIds.current.forEach(id => clearTimeout(id));
    };
  }, [handleKeyDown]);

  return (
    <List>
      {Array.from({ length: 12 }).map((_, i) => {
        const buildClassName = (classBase: string, isOnCooldown: boolean) => {
          return `${classBase} ${isOnCooldown ? 'onCooldown' : ''}`;
        };

        const isOnShortcutCooldown = shortcutCooldown > 0;

        if (shortcuts && shortcuts[i]?.type === ShortcutType.Item) {
          const payload = shortcuts[i]?.payload as IItem | undefined;

          let itemsFromEquipment: (IItem | undefined | null)[] = [];

          if (inventory) {
            Object.keys(inventory.slots).forEach(i => {
              const index = parseInt(i);

              if (inventory.slots[index]?.key === payload?.key) {
                itemsFromEquipment.push(inventory.slots[index]);
              }
            });
          }

          const totalQty =
            payload && inventory
              ? countItemFromInventory(payload.key, inventory)
              : 0;

          return (
            <StyledShortcut
              key={i}
              onPointerDown={handleShortcutCast.bind(null, i)}
              disabled={false}
              ref={el => {
                if (el) shortcutsRefs.current[i] = el;
              }}
            >
              {isOnShortcutCooldown && (
                <span className="cooldown">{shortcutCooldown.toFixed(1)}</span>
              )}
              {payload && (
                <SpriteFromAtlas
                  atlasIMG={atlasIMG}
                  atlasJSON={atlasJSON}
                  spriteKey={getItemTextureKeyPath(
                    {
                      key: payload.texturePath,
                      texturePath: payload.texturePath,
                      stackQty: payload.stackQty || 1,
                      isStackable: payload.isStackable,
                    },
                    atlasJSON
                  )}
                  width={32}
                  height={32}
                />
              )}
              <span className={buildClassName('qty', isOnShortcutCooldown)}>
                {totalQty}
              </span>
              <span
                className={buildClassName('keyboard', isOnShortcutCooldown)}
              >
                {i + 1}
              </span>
            </StyledShortcut>
          );
        }

        const payload =
          shortcuts && (shortcuts[i]?.payload as IRawSpell | undefined); //check if shortcuts exists before using the ? operator.

        const spellCooldown = !payload
          ? 0
          : spellCooldowns?.[payload.magicWords.replaceAll(' ', '_')] ??
            shortcutCooldown;
        const cooldown =
          spellCooldown > shortcutCooldown ? spellCooldown : shortcutCooldown;
        const isOnCooldown = cooldown > 0 && !!payload;

        const IMAGE_SCALE = 1.5;
        const IMAGE_SIZE = 32;

        return (
          <StyledShortcut
            key={i}
            onPointerDown={handleShortcutCast.bind(null, i)}
            disabled={mana < (payload?.manaCost ?? 0)}
            ref={el => {
              if (el) shortcutsRefs.current[i] = el;
            }}
          >
            {isOnCooldown && (
              <span className="cooldown">
                {cooldown.toFixed(cooldown < 10 ? 1 : 0)}
              </span>
            )}
            <span>
              {payload?.atlasIMG && (
                <SpriteFromAtlas
                  atlasIMG={payload.atlasIMG}
                  atlasJSON={payload.atlasJSON}
                  spriteKey={payload.texturePath ?? ''}
                  width={IMAGE_SIZE}
                  height={IMAGE_SIZE}
                  imgScale={IMAGE_SCALE}
                  centered
                  borderRadius="50%"
                />
              )}
            </span>
            <span className={buildClassName('mana', isOnCooldown)}>
              {payload && payload.manaCost}
            </span>
            <span className={buildClassName('keyboard', isOnCooldown)}>
              {i + 1}
            </span>
          </StyledShortcut>
        );
      })}
    </List>
  );
};

const StyledShortcut = styled(SingleShortcut)`
  transition: all 0.15s;

  &.active {
    background-color: ${uiColors.gray};
    border-color: ${uiColors.yellow};
  }
`;

const List = styled.p`
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
  box-sizing: border-box;
  margin: 0 !important;

  scale: 0.9;
`;
