import React, { useEffect, useState } from 'react';
import styled from 'styled-components';
import { uiFonts } from '../../constants/uiFonts';
import SelectArrow from '../Arrow/SelectArrow';
import { Ellipsis } from '../shared/Ellipsis';

export interface IPropertySelectProps {
  availableProperties: Array<IPropertiesProps>;
  selectedProperty?: IPropertiesProps;
  children?: React.ReactNode;
  onChange: (selectedProperty: IPropertiesProps) => void;
}

export interface IPropertiesProps {
  id: string;
  name: string;
}

export const PropertySelect: React.FC<IPropertySelectProps> = ({
  availableProperties,
  onChange,
}) => {
  const [currentIndex, setCurrentIndex] = useState(0);
  const propertiesLength = availableProperties.length - 1;

  const onLeftClick = () => {
    if (currentIndex === 0) setCurrentIndex(propertiesLength);
    else setCurrentIndex(index => index - 1);
  };
  const onRightClick = () => {
    if (currentIndex === propertiesLength) setCurrentIndex(0);
    else setCurrentIndex(index => index + 1);
  };

  useEffect(() => {
    onChange(availableProperties[currentIndex]);
  }, [currentIndex]);

  useEffect(() => {
    setCurrentIndex(0);
  }, [JSON.stringify(availableProperties)]);

  const getCurrentSelectionName = () => {
    const item = availableProperties[currentIndex];
    if (item) {
      return item.name;
    }
    return '';
  };

  return (
    <Container>
      <TextOverlay>
        <p>
          <Item>
            <Ellipsis maxLines={1} maxWidth="60%" center>
              {getCurrentSelectionName()}
            </Ellipsis>
          </Item>
        </p>
      </TextOverlay>
      <div className="rpgui-progress-track"></div>

      <SelectArrow direction="left" onPointerDown={onLeftClick}></SelectArrow>
      <SelectArrow direction="right" onPointerDown={onRightClick}></SelectArrow>
    </Container>
  );
};

const Item = styled.span`
  font-size: 1rem;
  color: white;
  text-align: center;
  z-index: 1;
  position: absolute;
  top: 12px;
  width: 100%;

  p {
    margin: 0 auto;
    font-size: ${uiFonts.size.small};
  }
`;

const TextOverlay = styled.div`
  width: 100%;
  position: relative;
`;

interface IContainerProps {
  percentageWidth?: number;
  minWidth?: number;
  style?: Record<string, any>;
}

const Container = styled.div<IContainerProps>`
  position: relative;
  display: flex;
  flex-direction: column;
  justify-content: start;
  align-items: flex-start;
  min-width: 100px;
  width: 40%;
`;

export default PropertySelect;
