import { useEffect, useRef, useState } from "react";
import { copyPresentationImage, getImageSrc } from "../../../ImageUtilities";
import {
  ElementComponent,
  ElementProps,
  ElementTypeName,
  ImageElementData,
  ShowHideDefaultVisibility,
} from "./types";
import useBaseElementStyles from "./hooks/useBaseElementStyles";
import useEditableFeatures from "./hooks/useEditableFeatures";

function Image(props: ElementProps<ImageElementData>) {
  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 {
    saveElement,
    element: {
      name,
      src,
      enableBoxShadow,
      opacity,
      constrainAspectRatio,
      width,
      height,
    },
  } = props;
  // for useEffect
  const element = props.element;

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

  useEffect(() => {
    if (!wasConstrained && constrainAspectRatio) {
      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,
  ]);

  return (
    <div className={baseClasses} style={baseStyles} {...moveListeners}>
      <img
        ref={imgRef}
        alt={name}
        style={{
          width: baseStyles.width,
          height: baseStyles.height,
          position: "absolute",
          opacity: `${opacity}%`,
          boxShadow: enableBoxShadow ? "0 0 5px #000000" : "none",
        }}
        crossOrigin="anonymous"
        draggable={!props.isEditable}
        onDragStart={(e) => props.isEditable && e.preventDefault()}
        src={getImageSrc(src)}
      />
      {resizeHandles}
    </div>
  );
}

const ImageForExport = Image as unknown as ElementComponent<ImageElementData>;

ImageForExport.elementName = "Image";
ImageForExport.description = "An element for displaying images or logos.";
ImageForExport.icon = "image";
ImageForExport.blankFactory = (newId, newZ, data) => ({
  type: ElementTypeName.Image,
  name: "New Image",

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

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

  src: null,
  constrainAspectRatio: true,
  thumbnail: true,

  opacity: 100,
  enableBoxShadow: false,

  visible: {
    default: ShowHideDefaultVisibility.Show,
    except: [],
  },
});
ImageForExport.clone = (
  source,
  newId,
  newName,
  newZ,
  data,
  deferredUpdater,
  showToast,
) => {
  showToast(<span>Copying image...</span>, "info");

  copyPresentationImage(source.src, data.metadata.token, newId, "image").then(
    (newSrc) => {
      deferredUpdater({ src: newSrc });

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

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

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

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

    src: null,
    constrainAspectRatio: source.constrainAspectRatio,
    thumbnail: source.thumbnail,

    opacity: source.opacity,
    enableBoxShadow: source.enableBoxShadow,

    visible: source.visible,
  };
};

export default ImageForExport;
