import React, { useEffect, useState } from 'react';
import styled from 'styled-components';
import SelectArrow from '../Arrow/SelectArrow';
import { ErrorBoundary } from '../Item/Inventory/ErrorBoundary';
import { SpriteFromAtlas } from '../shared/SpriteFromAtlas';
import { ICharacterProps } from './CharacterSelection';

export interface ISkinSelectionGridProps {
  availableCharacters: ICharacterProps[];
  initialSelectedSkin?: string;
  onChange: (skinKey: string) => void;
  atlasJSON: any;
  atlasIMG: any;
}

export const SkinSelectionGrid: React.FC<ISkinSelectionGridProps> = ({
  availableCharacters,
  initialSelectedSkin = '',
  onChange,
  atlasJSON,
  atlasIMG,
}) => {
  const [currentIndex, setCurrentIndex] = useState(0);
  
  // Find the initial index based on initialSelectedSkin
  useEffect(() => {
    if (initialSelectedSkin && availableCharacters.length > 0) {
      const initialIndex = availableCharacters.findIndex(
        character => character.textureKey === initialSelectedSkin
      );
      if (initialIndex !== -1) {
        setCurrentIndex(initialIndex);
      }
    }
  }, [initialSelectedSkin, availableCharacters]);
  
  // Update the selected skin when currentIndex changes
  useEffect(() => {
    if (availableCharacters.length > 0) {
      const selectedCharacter = availableCharacters[currentIndex];
      onChange(selectedCharacter.textureKey);
    }
  }, [currentIndex, availableCharacters, onChange]);

  const handlePrevious = () => {
    setCurrentIndex((prevIndex) => 
      prevIndex === 0 ? availableCharacters.length - 1 : prevIndex - 1
    );
  };

  const handleNext = () => {
    setCurrentIndex((prevIndex) => 
      prevIndex === availableCharacters.length - 1 ? 0 : prevIndex + 1
    );
  };

  const getSpriteKey = (textureKey: string) => {
    return textureKey + '/down/standing/0.png';
  };

  if (availableCharacters.length === 0) {
    return <Container>No skins available</Container>;
  }

  const currentCharacter = availableCharacters[currentIndex];

  return (
    <Container>
      <Header>Select Your Character Skin</Header>
      <CarouselContainer>
        <NavButtonWrapper>
          <SelectArrow 
            direction="left" 
            onPointerDown={handlePrevious}
          />
        </NavButtonWrapper>
        
        <SkinPreview>
          {currentCharacter && (
            <>
              <ErrorBoundary>
                <SpriteFromAtlas
                  spriteKey={getSpriteKey(currentCharacter.textureKey)}
                  atlasIMG={atlasIMG}
                  atlasJSON={atlasJSON}
                  imgScale={4}
                  height={80}
                  width={64}
                  containerStyle={{
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                  }}
                  imgStyle={{
                    position: 'relative',
                    left: 0,
                  }}
                />
              </ErrorBoundary>
              <SkinName>{currentCharacter.name}</SkinName>
            </>
          )}
        </SkinPreview>
        
        <NavButtonWrapper>
          <SelectArrow 
            direction="right" 
            onPointerDown={handleNext}
          />
        </NavButtonWrapper>
      </CarouselContainer>
      
      <CounterIndicator>
        {currentIndex + 1} / {availableCharacters.length}
      </CounterIndicator>
    </Container>
  );
};

const Container = styled.div`
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
  margin-top: 1rem;
  image-rendering: pixelated;
`;

const Header = styled.h3`
  margin: 0 0 1rem 0;
  color: white;
  text-align: center;
  font-size: 1.1rem;
`;

const CarouselContainer = styled.div`
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  margin-bottom: 0.5rem;
  position: relative;
`;

const SkinPreview = styled.div`
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 1rem;
  background-color: rgba(245, 158, 11, 0.1);
  border: 2px solid #f59e0b;
  border-radius: 8px;
  width: 140px;
  height: 150px;
  margin: 0 1.5rem;
`;

const SkinName = styled.span`
  color: white;
  font-size: 1rem;
  margin-top: 0.8rem;
  text-align: center;
  font-weight: bold;
`;

const NavButtonWrapper = styled.div`
  width: 40px;
  height: 42px;
  position: relative;
`;

const CounterIndicator = styled.div`
  color: white;
  font-size: 0.8rem;
  margin-top: 0.5rem;
`;

export default SkinSelectionGrid; 