import classNames from "classnames/dedupe";
import { useEffect, useRef, useState } from "react";
import { mergeRefs } from "../../utils";
import {
  REQUIRED_TRUSTPILOT_CLASS_NAME,
  SIMPLYBUSINESS_UNIT_ID,
  SIMPLYBUSINESS_UNIT_IDS,
  TRUSTPILOT_LINKS,
  TRUSTPILOT_WIDGET,
} from "./constants";
import type { TrustProps } from "./types";

export const Trust = ({ ref, ...props }: TrustProps) => {
  const {
    elementType: Element = "div",
    variant,
    theme,
    locale,
    height,
    width,
    stars,
    className,
  } = props;
  const [isMounted, setIsMounted] = useState(false);
  const trustRef = useRef(null);

  const {
    templateId,
    className: variantClassName,
    styles,
  } = TRUSTPILOT_WIDGET[variant];
  const link = TRUSTPILOT_LINKS[locale];
  const businessUnitId =
    SIMPLYBUSINESS_UNIT_IDS[locale] || SIMPLYBUSINESS_UNIT_ID;

  const dataProps = {
    "data-businessunit-id": businessUnitId,
    "data-locale": locale,
    "data-template-id": templateId,
    "data-theme": theme,
    "data-style-width": width || "100%",
    "data-style-height": height,
    "data-stars": stars,
  };

  const classes = classNames(
    "mobius",
    "mobius-trust",
    REQUIRED_TRUSTPILOT_CLASS_NAME,
    {
      [`--is-${theme}`]: theme,
      [variantClassName]: variant,
    },
    className,
  );

  useEffect(() => {
    const hasTrustpilotLoaded =
      trustRef.current &&
      window?.Trustpilot &&
      window?.Trustpilot.loadFromElement;
    // If window.Trustpilot is available it means that we need to load the TrustBox from our ref.
    if (isMounted && hasTrustpilotLoaded) {
      window.Trustpilot.loadFromElement(trustRef.current, true);
    }
  }, [isMounted]);

  useEffect(() => {
    setIsMounted(true);
  }, []);

  // Load `<Trust>` client-side only to avoid SSR hydration issues
  if (!isMounted) return <div style={styles} />;

  return (
    <Element
      ref={mergeRefs([trustRef, ref])}
      className={classes}
      style={styles}
      {...dataProps}
    >
      <a
        href={link}
        target="_blank"
        rel="noopener noreferrer"
        className="mobius-trust__link"
      >
        Trustpilot
      </a>
    </Element>
  );
};
