import { IShortcut, ISpell } from '@rpg-engine/shared';
import React, { Fragment, useMemo, useState } from 'react';
import styled from 'styled-components';
import { uiFonts } from '../../constants/uiFonts';
import { DraggableContainer } from '../DraggableContainer';
import { Input } from '../Input';
import { RPGUIContainerTypes } from '../RPGUI/RPGUIContainer';
import { ShortcutsSetter } from '../Shortcuts/ShortcutsSetter';
import { Spell } from './Spell';

export interface ISpellbookProps {
  onClose?: () => void;
  onInputFocus?: () => void;
  onInputBlur?: () => void;
  spells: ISpell[];
  magicLevel: number;
  mana: number;
  onSpellClick: (spellKey: string) => void;
  setSpellShortcut: (key: string, index: number) => void;
  shortcuts: IShortcut[];
  removeShortcut: (index: number) => void;
  atlasIMG: any;
  atlasJSON: any;
  iconAtlasIMG?: any;
  iconAtlasJSON?: any;
  scale?: number;
  spellCooldowns?: Record<string, number>;
}

export const Spellbook: React.FC<ISpellbookProps> = ({
  onClose,
  onInputFocus,
  onInputBlur,
  spells,
  magicLevel,
  mana,
  onSpellClick,
  setSpellShortcut,
  shortcuts,
  removeShortcut,
  atlasIMG,
  atlasJSON,
  iconAtlasIMG,
  iconAtlasJSON,
  scale,
  spellCooldowns,
}) => {
  const [search, setSearch] = useState('');
  const [settingShortcutIndex, setSettingShortcutIndex] = useState(-1);

  const spellsToDisplay = useMemo(() => {
    return spells
      .sort((a, b) => {
        if (a.minMagicLevelRequired > b.minMagicLevelRequired) return 1;
        if (a.minMagicLevelRequired < b.minMagicLevelRequired) return -1;
        return 0;
      })
      .filter(
        spell =>
          spell.name.toLocaleLowerCase().includes(search.toLocaleLowerCase()) ||
          spell.magicWords
            .toLocaleLowerCase()
            .includes(search.toLocaleLowerCase())
      );
  }, [search, spells]);

  const setShortcut = (spellKey: string) => {
    setSpellShortcut?.(spellKey, settingShortcutIndex);
    setSettingShortcutIndex(-1);
  };

  return (
    <DraggableContainer
      type={RPGUIContainerTypes.Framed}
      onCloseButton={onClose}
      width="inherit"
      height="inherit"
      cancelDrag="#spellbook-search, #shortcuts_list, .spell"
      scale={scale}
    >
      <Container>
        <Title>Learned Spells</Title>

        <ShortcutsSetter
          setSettingShortcutIndex={setSettingShortcutIndex}
          settingShortcutIndex={settingShortcutIndex}
          shortcuts={shortcuts}
          removeShortcut={removeShortcut}
          atlasIMG={atlasIMG}
          atlasJSON={atlasJSON}
        />

        <Input
          placeholder="Search for spell"
          value={search}
          onChange={e => setSearch(e.target.value)}
          onFocus={onInputFocus}
          onBlur={onInputBlur}
          id="spellbook-search"
        />

        <SpellList>
          {spellsToDisplay.map(spell => (
            <Fragment key={spell.key}>
              <Spell
                atlasIMG={iconAtlasIMG}
                atlasJSON={iconAtlasJSON}
                charMana={mana}
                charMagicLevel={magicLevel}
                onPointerUp={
                  settingShortcutIndex !== -1 ? setShortcut : onSpellClick
                }
                spellKey={spell.key}
                isSettingShortcut={settingShortcutIndex !== -1}
                spell={spell}
                activeCooldown={
                  spellCooldowns?.[spell.magicWords.replaceAll(' ', '_')]
                }
                {...spell}
              />
            </Fragment>
          ))}
        </SpellList>
      </Container>
    </DraggableContainer>
  );
};

const Title = styled.h1`
  font-size: ${uiFonts.size.large} !important;
  margin-bottom: 0 !important;
`;

const Container = styled.div`
  width: 100%;
  height: 100%;
  color: white;
  display: flex;
  flex-direction: column;
`;

const SpellList = styled.div`
  width: 100%;
  min-height: 0;
  flex: 1;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
  margin-top: 1rem;
`;
