import { convert as colorConvert } from "chromatism";
import { useEffect, useState } from "react";
import {
  ElementComponent,
  ElementProps,
  ElementTypeName,
  RectangleElementData,
  ShowHideDefaultVisibility,
} from "./types";
import useBaseElementStyles from "./hooks/useBaseElementStyles";
import useEditableFeatures from "./hooks/useEditableFeatures";

function Rectangle(props: ElementProps<RectangleElementData>) {
  const { resizeHandles, moveListeners, currentDimensions } =
    useEditableFeatures(props);
  const { baseClasses, baseStyles } = useBaseElementStyles(
    currentDimensions,
    props.scaleFactor,
    props.isEditable,
  );

  const [rgba, setRgba] = useState<string>("");

  const { color, opacity, width, height, borderRadius } = props.element;

  useEffect(() => {
    const rgb = colorConvert(color).rgb;
    setRgba(`rgba(${rgb.r},${rgb.g},${rgb.b},${opacity / 100})`);
  }, [color, opacity]);

  return (
    <div
      className={baseClasses}
      style={{
        ...baseStyles,
        backgroundColor: rgba,
        borderRadius: `${
          ((Math.min(width, height) * borderRadius) / 100 / 2) *
          props.scaleFactor
        }px`,
      }}
      {...moveListeners}
    >
      {resizeHandles}
    </div>
  );
}

const RectangleForExport =
  Rectangle as unknown as ElementComponent<RectangleElementData>;

RectangleForExport.elementName = "Solid Rectangle";
RectangleForExport.description = "A solid rectangular box shape.";
RectangleForExport.icon = "rectangle";
RectangleForExport.blankFactory = (newId, newZ, data) => ({
  type: ElementTypeName.Rectangle,
  name: "New Rectangle",

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

  isLocked: false,
  width: 100,
  height: 100,

  opacity: 100,
  borderRadius: 0,

  color: "#000000",

  visible: {
    default: ShowHideDefaultVisibility.Show,
    except: [],
  },
});
RectangleForExport.clone = (source, newId, newName, newZ) => ({
  type: ElementTypeName.Rectangle,
  name: newName,

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

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

  opacity: source.opacity,
  borderRadius: source.borderRadius,

  color: source.color,

  visible: source.visible,
});

export default RectangleForExport;
