import React, { useEffect, useState } from 'react';
import styled from 'styled-components';

import { SpriteFromAtlas } from '../shared/SpriteFromAtlas';

import { ErrorBoundary } from '../Item/Inventory/ErrorBoundary';
import PropertySelect, {
  IPropertiesProps,
} from '../PropertySelect/PropertySelect';

export interface ICharacterProps {
  name: string;
  textureKey: string;
}

export interface ICharacterSelectionProps {
  availableCharacters: ICharacterProps[];
  atlasJSON: any;
  atlasIMG: any;
  onChange: (textureKey: string) => void;
}

export const CharacterSelection: React.FC<ICharacterSelectionProps> = ({
  availableCharacters,
  atlasJSON,
  atlasIMG,
  onChange,
}) => {
  const propertySelectValues = availableCharacters.map((item) => {
    return {
      id: item.textureKey,
      name: item.name,
    };
  });

  const [selectedValue, setSelectedValue] = useState<IPropertiesProps>();
  const [selectedSpriteKey, setSelectedSpriteKey] = useState('');

  const onSelectedValueChange = () => {
    const textureKey = selectedValue ? selectedValue.id : '';
    const spriteKey = textureKey ? textureKey + '/down/standing/0.png' : '';

    if (spriteKey === selectedSpriteKey) {
      return;
    }

    setSelectedSpriteKey(spriteKey);
    onChange(textureKey);
  };

  useEffect(() => {
    onSelectedValueChange();
  }, [selectedValue]);

  useEffect(() => {
    setSelectedValue(propertySelectValues[0]);
  }, [availableCharacters]);

  return (
    <Container>
      {selectedSpriteKey && atlasIMG && atlasJSON && (
        <ErrorBoundary>
          <SpriteFromAtlas
            spriteKey={selectedSpriteKey}
            atlasIMG={atlasIMG}
            atlasJSON={atlasJSON}
            imgScale={4}
            height={80}
            width={64}
            containerStyle={{
              display: 'flex',
              alignItems: 'center',
              paddingBottom: '15px',
            }}
            imgStyle={{
              left: '22px',
            }}
          />
        </ErrorBoundary>
      )}
      <PropertySelect
        availableProperties={propertySelectValues}
        onChange={(value) => {
          setSelectedValue(value);
        }}
      />
    </Container>
  );
};

const Container = styled.div`
  display: flex;
  flex-direction: column;
  align-items: center;
  image-rendering: pixelated;
`;

export default CharacterSelection;
