import shadowRoot from "react-shadow";
import {
  CustomHtmlElementData,
  ElementComponent,
  ElementProps,
  ElementTypeName,
  ShowHideDefaultVisibility,
} from "./types";
import useBaseElementStyles from "./hooks/useBaseElementStyles";
import useEditableFeatures from "./hooks/useEditableFeatures";

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

  const { html, scale, shadow } = props.element;

  const Component = shadow ? shadowRoot.div : "div";

  const userScaleFactor = (props.scaleFactor * scale) / 100;

  return (
    <div
      className={baseClasses}
      style={{
        ...baseStyles,
      }}
      {...moveListeners}
    >
      <Component
        style={{
          position: "absolute",
          width: `calc(100% * ${1 / userScaleFactor})`,
          height: `calc(100% * ${1 / userScaleFactor})`,
          transform: `scale(${userScaleFactor})`,
          transformOrigin: "0 0",
        }}
      >
        {/* eslint-disable-next-line react/no-danger */}
        <div dangerouslySetInnerHTML={{ __html: html }} />
      </Component>
      {resizeHandles}
    </div>
  );
}

const CustomHtmlForExport =
  CustomHtml as unknown as ElementComponent<CustomHtmlElementData>;

CustomHtmlForExport.elementName = "Custom HTML";
CustomHtmlForExport.description =
  "A container which allows for custom HTML to be directly added to the presentation.";
CustomHtmlForExport.icon = "custom-html";
CustomHtmlForExport.blankFactory = (newId, newZ, data) => ({
  type: ElementTypeName.CustomHtml,
  name: "New Custom HTML",

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

  isLocked: false,
  width: 500,
  height: 300,
  scale: 100,

  html:
    "<p>\n" +
    "  This is a custom element. When sandboxed the element will look exactly as\n" +
    "  it does in the preview at any screen size!\n" +
    "</p>",
  shadow: true,

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

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

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

  html: source.html,
  shadow: source.shadow,

  visible: source.visible,
});

export default CustomHtmlForExport;
