import React, { useEffect, useState } from "react";

import Image from "@enact/sandstone/Image";
import Spottable from "@enact/spotlight/Spottable";

import css from "./Indicator.module.less";

const SpottableComponent = Spottable("button");

export default function Indicator({ images }) {
  const [selectedImage, setSelectedImage] = useState(null);
  const [selectedIndex, setSelectedIndex] = useState(0);

  useEffect(() => {
    if (images && images.length > 0) {
      setSelectedImage(images[0]);
    }
  }, [images]);

  const handlePrevClick = () => {
    setSelectedImage((prevSelectedImage) => {
      const currentIndex = images.indexOf(prevSelectedImage);
      return currentIndex === 0
        ? images[images.length - 1]
        : images[currentIndex - 1];
    });
  };

  const handleNextClick = () => {
    setSelectedImage((prevSelectedImage) => {
      const currentIndex = images.indexOf(prevSelectedImage);
      return currentIndex === images.length - 1
        ? images[0]
        : images[currentIndex + 1];
    });
  };

  const handleItemClick = (image) => {
    setSelectedImage(image);
  };

  return (
    <div className={css.Wrap}>
      <div>
        {images && <img src={selectedImage} alt="" className={css.thumbnail} />}
      </div>
      <div>
        <SpottableComponent
          onClick={handlePrevClick}
          className={css.upButton}
        />
        {images &&
          images
            .slice(0, 3)
            .map((image, index) => (
              <Image
                key={index}
                src={image}
                alt={""}
                onClick={() => handleItemClick(image)}
                selected={selectedIndex === index}
                className={css.image}
              />
            ))}
        <SpottableComponent
          className={css.downButton}
          onClick={handleNextClick}
        />
      </div>
    </div>
  );
}
