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

interface DataImage {
  src: string;
}

interface Props {
  images: Array<DataImage>;
  isLogo: boolean;
  delay?: number;
}

const Carousel = (props: Props) => {
  const { images, isLogo, delay } = props;
  const [index, setIndex] = useState(1);

  const nbr_image: number = images.length;

  const updateIndex = (newIndex: number) => {
    if (newIndex < 0) {
      newIndex = nbr_image - 1;
    } else if (newIndex >= nbr_image) {
      newIndex = 0;
    }

    setIndex(newIndex);
  };

  useEffect(() => {
    const interval = setInterval(() => {
      if (delay != 0) {
        updateIndex(index + 1);
      }
    }, delay);

    return () => {
      if (interval) {
        clearInterval(interval);
      }
    };
  });

  return (
    <div className="block relative">
      <div
        className={`carousel ${isLogo ? "w-1/4 ml-7" : "w-full"} truncate`}
      >
        <div
          className={`whitespace-nowrap ${isLogo ? "w-1/2" : "w-full"} `}
          style={{
            transform:
             isLogo ?
              nbr_image > 2
                ? `translateX(-${index * 60 }%)`
                : `translateX(0)`
                : `translateX(-${index * 100}%)`,
            transition: "transform 0.3s",
          }}
        >
          {images.map((item: any, key: any) => {
            return (
              <div
                className={`carousel-item relative w-full inline-block`}
                key={key}
              >
                {isLogo ? (
                  <div className="flex justify-center items-center w-full">
                    <img
                      src={item.src}
                      className="w-28 h-28 border border-gray-600"
                    />
                  </div>
                ) : (
                  <img src={item.src} className="w-full h-[384px]" />
                )}
              </div>
            );
          })}
        </div>
      </div>
      <div
        className={`absolute flex justify-between pl-5 pr-5 ${
          isLogo ? "w-[30%]" : "w-full"
        }  ${isLogo ? "top-9" : "top-[47%]"} `}
      >
        <button
          onClick={() => updateIndex(index - 1)}
          className={`bg-neutral rounded-3xl  ${
            isLogo ? "w-5" : "w-10"
          } h-10 text-base-100`}
        >
          ❮
        </button>
        <button
          onClick={() => updateIndex(index + 1)}
          className={`bg-neutral rounded-3xl  ${
            isLogo ? "w-5" : "w-10"
          } h-10 text-base-100`}
        >
          ❯
        </button>
      </div>
    </div>
  );
};

export default Carousel;