import { Splide, SplideSlide } from "@splidejs/react-splide";
import { useEffect, useRef, useState } from "react";
import { Textfit } from "react-textfit";
import { v4 as uuid } from "uuid";
import { copyPresentationImage, getImageSrc } from "../../../ImageUtilities";
import objectToArray from "../../../utils/objectToArray";
import {
  ElementComponent,
  ElementProps,
  ElementTypeName,
  ImageSlideshowElementData,
  ImageSlideshowImage,
} from "./types";
import shouldElementBeShown from "../shouldElementBeShown";
import useBaseElementStyles from "./hooks/useBaseElementStyles";
import useEditableFeatures from "./hooks/useEditableFeatures";

import "@splidejs/react-splide/css";

function ImageSlideshow(props: ElementProps<ImageSlideshowElementData>) {
  const imgRef = useRef<HTMLImageElement | null>(null);

  const { resizeHandles, moveListeners, currentDimensions } =
    useEditableFeatures(
      props,
      props.element.constrainAspectRatio && imgRef.current
        ? imgRef.current.naturalWidth / imgRef.current.naturalHeight
        : undefined,
    );
  const { baseClasses, baseStyles } = useBaseElementStyles(
    currentDimensions,
    props.scaleFactor,
    props.isEditable,
  );

  const {
    isEditable,
    saveElement,
    viewTime,
    element: {
      name,
      images,
      constrainAspectRatio,
      width,
      height,
      arrows,
      pageIndicators,
      backgroundColor,
    },
  } = props;
  // for useEffect
  const element = props.element;

  const [wasConstrained, setWasConstrained] =
    useState<boolean>(constrainAspectRatio);

  useEffect(() => {
    if (!wasConstrained && constrainAspectRatio && isEditable) {
      const realRatio =
        imgRef.current.naturalWidth / imgRef.current.naturalHeight;
      const curRatio = width / height;

      // allow 1% tolerance
      if (Math.abs(realRatio / curRatio) > 0.01) {
        // only make smaller, not bigger
        const newWidth = height * realRatio;
        const newHeight = width / realRatio;

        if (newWidth < width) {
          saveElement({ ...element, width: newWidth });
        } else {
          saveElement({ ...element, height: newHeight });
        }
      }
    }

    if (wasConstrained !== constrainAspectRatio) {
      setWasConstrained(constrainAspectRatio);
    }
  }, [
    wasConstrained,
    constrainAspectRatio,
    height,
    width,
    element,
    saveElement,
    isEditable,
  ]);

  const [visibleImages, setVisibleImages] = useState(
    objectToArray(images).filter((image) =>
      shouldElementBeShown(image.visible, props.viewTime),
    ),
  );

  useEffect(() => {
    const newImages = objectToArray(images).filter((image) =>
      shouldElementBeShown(image.visible, viewTime),
    );
    if (JSON.stringify(newImages) !== JSON.stringify(visibleImages)) {
      setVisibleImages(newImages);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [viewTime, images]);

  const splide = useRef<Splide | null>(null);

  useEffect(() => {
    if (splide.current?.splide.length > 1) {
      const curImage = visibleImages[splide.current.splide.index];

      const newTimeout = window.setTimeout(
        () => splide.current.splide.go(">"),
        curImage.delay * 1000,
      );

      return () => clearTimeout(newTimeout);
    }

    return () => ({});
  }, [splide.current?.splide.index, visibleImages]);

  return (
    <div
      className={baseClasses}
      style={{ ...baseStyles, backgroundColor }}
      {...moveListeners}
    >
      <Splide
        ref={splide}
        aria-label={name}
        options={{
          fixedWidth: baseStyles.width,
          fixedHeight: baseStyles.height,
          perPage: 1,
          type: "loop",
          arrows,
          pagination: pageIndicators,
        }}
      >
        {visibleImages.map((img, i) => (
          <SplideSlide key={img.src}>
            <img
              ref={i === 0 ? imgRef : undefined}
              src={getImageSrc(img.src)}
              crossOrigin="anonymous"
              aria-label={name}
              style={{ objectFit: "contain", width: "100%", height: "100%" }}
            />
            <span>{img.caption}</span>
          </SplideSlide>
        ))}
        {visibleImages.length === 0 ? (
          <SplideSlide key="empty">
            <Textfit
              style={{
                backgroundColor: "#ccc",
                border: "1px solid black",
                position: "absolute",
                width: "100%",
                height: "100%",
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
                textAlign: "center",
              }}
            >
              Please add images to this slideshow
            </Textfit>
          </SplideSlide>
        ) : undefined}
      </Splide>
      {resizeHandles}
    </div>
  );
}

const ImageForExport =
  ImageSlideshow as unknown as ElementComponent<ImageSlideshowElementData>;

ImageForExport.elementName = "Image Slideshow";
ImageForExport.description =
  "An element which rotates through a series of custom images.";
ImageForExport.icon = "imageset";
ImageForExport.blankFactory = (newId, newZ, data) => ({
  type: ElementTypeName.ImageSlideshow,
  name: "New Image Slideshow",

  id: newId,
  x: data.metadata.width / 2 - 175,
  y: data.metadata.height / 2 - 100,
  z: newZ,

  isLocked: false,
  width: 350,
  height: 200,

  constrainAspectRatio: true,
  defaultDelay: 5,

  backgroundColor: "transparent",
  arrows: true,
  pageIndicators: true,

  images: [],
});
ImageForExport.clone = (
  source,
  newId,
  newName,
  newZ,
  data,
  deferredUpdater,
  showToast,
) => {
  (async () => {
    const newImages: ImageSlideshowImage[] = [];
    const sourceImages = objectToArray(source.images);

    for (const image of sourceImages) {
      showToast(
        <span>
          Copying image {newImages.length + 1} of {sourceImages.length}
        </span>,
        "info",
      );

      const newSrc = await copyPresentationImage(
        image.src,
        data.metadata.token,
        newId,
        uuid(),
      );

      newImages.push({ ...image, src: newSrc });
      deferredUpdater({ images: newImages });
    }

    showToast(<span>Element copied!</span>, "success");
  })();

  return {
    type: ElementTypeName.ImageSlideshow,
    name: newName,

    id: newId,
    x: source.x,
    y: source.y,
    z: newZ,

    isLocked: source.isLocked,
    width: source.width,
    height: source.height,

    constrainAspectRatio: source.constrainAspectRatio,
    defaultDelay: source.defaultDelay,

    backgroundColor: source.backgroundColor,
    arrows: source.arrows,
    pageIndicators: source.pageIndicators,

    images: [],
  };
};
export default ImageForExport;
