import React, { useEffect, useState } from 'react';
import styled from 'styled-components';
import { Button, ButtonTypes } from '../Button';
import { ErrorBoundary } from '../Item/Inventory/ErrorBoundary';
import PropertySelect, {
  IPropertiesProps,
} from '../PropertySelect/PropertySelect';
import { SpriteFromAtlas } from '../shared/SpriteFromAtlas';
import { ICharacterProps } from './CharacterSelection';

export interface ICharacterSkinSelectionModalProps {
  isOpen: boolean;
  onClose: () => void;
  onConfirm: (textureKey: string) => void;
  availableCharacters: ICharacterProps[];
  atlasJSON: any;
  atlasIMG: any;
  initialSelectedSkin?: string;
}

export const CharacterSkinSelectionModal: React.FC<ICharacterSkinSelectionModalProps> = ({
  isOpen,
  onClose,
  onConfirm,
  availableCharacters,
  atlasJSON,
  atlasIMG,
  initialSelectedSkin = '',
}) => {
  // Convert availableCharacters to the format used by PropertySelect
  const propertySelectValues = availableCharacters.map(item => ({
    id: item.textureKey,
    name: item.name,
  }));

  // State to store the selected skin and the sprite key
  const [selectedValue, setSelectedValue] = useState<
    IPropertiesProps | undefined
  >();
  const [selectedSpriteKey, setSelectedSpriteKey] = useState('');

  // Update sprite when the selected value changes
  const updateSelectedSpriteKey = () => {
    const textureKey = selectedValue ? selectedValue.id : '';
    const spriteKey = textureKey ? textureKey + '/down/standing/0.png' : '';

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

    setSelectedSpriteKey(spriteKey);
  };

  // Update sprite when selectedValue changes
  useEffect(() => {
    updateSelectedSpriteKey();
  }, [selectedValue]);

  // Initialize selectedValue
  useEffect(() => {
    if (initialSelectedSkin) {
      const initialProperty = propertySelectValues.find(
        prop => prop.id === initialSelectedSkin
      );
      setSelectedValue(initialProperty || propertySelectValues[0]);
    } else if (propertySelectValues.length > 0) {
      setSelectedValue(propertySelectValues[0]);
    }
  }, [initialSelectedSkin, availableCharacters]);

  // Functions to handle confirmation and cancellation
  const handleConfirm = () => {
    if (selectedValue) {
      onConfirm(selectedValue.id);
      onClose();
    }
  };

  const handleCancel = () => {
    onClose();
  };

  if (!isOpen) return null;

  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);
        }}
      />

      <ButtonsContainer>
        <Button buttonType={ButtonTypes.RPGUIButton} onClick={handleCancel}>
          Cancel
        </Button>
        <Button
          buttonType={ButtonTypes.RPGUIButton}
          onClick={handleConfirm}
          disabled={!selectedValue}
        >
          Confirm
        </Button>
      </ButtonsContainer>
    </Container>
  );
};

// Styled components

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

const ButtonsContainer = styled.div`
  display: flex;
  justify-content: center;
  gap: 0.8rem;
  width: 100%;
  margin: 3rem 0 0.75rem;

  button {
    min-width: 95px;
    font-size: 0.9rem;
  }
`;
