import { IRawSpell, IShortcut, ShortcutType } from '@rpg-engine/shared';
import { Meta, Story } from '@storybook/react';
import React, { useEffect, useState } from 'react';
import { RPGUIRoot } from '../../../components/RPGUI/RPGUIRoot';
import {
  ISpellbookProps,
  Spellbook,
} from '../../../components/Spellbook/Spellbook';
import {
  SHORTCUTS_STORAGE_KEY,
  defaultShortcut,
} from '../../../components/Spellbook/constants';
import { mockSpells } from '../../../components/Spellbook/mockSpells';
import atlasJSON from '../../../mocks/atlas/items/items.json';
import atlasIMG from '../../../mocks/atlas/items/items.png';

const meta: Meta = {
  title: 'Features/Spells/Spellbook',
  component: Spellbook,
};

export default meta;

const Template: Story<ISpellbookProps> = args => {
  const [shortcuts, setShortcuts] = useState<IShortcut[]>([]);

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

  const setSpellShortcut = (key: string, index: number) => {
    const shortcuts = JSON.parse(
      localStorage.getItem(SHORTCUTS_STORAGE_KEY) as string
    ) as IShortcut[];

    const spell = mockSpells.find(s => s.key === key);
    if (!spell) {
      return;
    }

    const spellRaw = {
      ...spell,
      atlasIMG: atlasIMG,
      atlasJSON: atlasIMG,
    } as IRawSpell;

    if (!shortcuts) {
      const newShortcuts: IShortcut[] = Array(6).fill(defaultShortcut);

      newShortcuts[index] = {
        type: ShortcutType.Spell,
        payload: spellRaw,
      };

      localStorage.setItem(SHORTCUTS_STORAGE_KEY, JSON.stringify(newShortcuts));
    } else {
      shortcuts[index] = {
        type: ShortcutType.Spell,
        payload: spellRaw,
      };

      localStorage.setItem(SHORTCUTS_STORAGE_KEY, JSON.stringify(shortcuts));
    }

    setShortcuts(shortcuts);
  };

  const removeShortcut = (index: number) => {
    const shortcuts = JSON.parse(
      localStorage.getItem(SHORTCUTS_STORAGE_KEY) as string
    );

    if (!shortcuts) return;

    shortcuts[index] = defaultShortcut;

    localStorage.setItem(SHORTCUTS_STORAGE_KEY, JSON.stringify(shortcuts));

    setShortcuts(shortcuts);
  };

  return (
    <RPGUIRoot>
      <div
        style={{
          width: '50%',
          height: '75%',
        }}
      >
        <Spellbook
          {...args}
          setSpellShortcut={setSpellShortcut}
          removeShortcut={removeShortcut}
          shortcuts={shortcuts}
        />
      </div>
    </RPGUIRoot>
  );
};

export const Default = Template.bind({});
Default.args = {
  onClose: () => console.log('close'),
  onSpellClick: spellKey => console.log(spellKey),
  spells: mockSpells,
  magicLevel: 3,
  mana: 5,
  atlasIMG,
  atlasJSON,
};
