import React, { useEffect, useState } from 'react';
import styled from 'styled-components';
import { Button, ButtonTypes } from '../Button';
import { ICharacterProps } from './CharacterSelection';
import { SkinSelectionGrid } from './SkinSelectionGrid';

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 = '',
}) => {
  const [selectedSkin, setSelectedSkin] = useState(initialSelectedSkin);

  // Initialize selected skin
  useEffect(() => {
    if (initialSelectedSkin) {
      setSelectedSkin(initialSelectedSkin);
    } else if (availableCharacters.length > 0) {
      setSelectedSkin(availableCharacters[0].textureKey);
    }
  }, [initialSelectedSkin, availableCharacters]);

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

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

  if (!isOpen) return null;

  return (
    <Container>
      <SkinSelectionGrid
        availableCharacters={availableCharacters}
        initialSelectedSkin={selectedSkin}
        onChange={setSelectedSkin}
        atlasJSON={atlasJSON}
        atlasIMG={atlasIMG}
      />

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

// Styled components
const Container = styled.div`
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 400px;
  max-width: 100%;
  image-rendering: pixelated;
`;

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

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