import { useRef } from "react";
import clsx from "clsx";
import { m } from "framer-motion";

import CallToAction from "@/components/call-to-action";
import stylesCta from "@/components/call-to-action/styles.module.scss";
import Image from "@/components/image";
import { brightness, getContrastYIQ } from "@/helpers/color";
import type { CtaBlock } from "@/types";

import styles from "./styles.module.scss";

type CtaBlockProps = CtaBlock;

export default function CTA({
  id,
  buttonText,
  ctaLink,
  newtab = true,
  colorAuto,
  color,
  bgColor,
  title,
  align = "left",
  image,
}: CtaBlockProps) {
  const ctaRef = useRef<HTMLDivElement>(null);

  type CustomCSSProperties = React.CSSProperties & {
    "--bg-color"?: string;
    "--bg-color-hover"?: string;
    "--color"?: string;
  };

  const ctaClasses = clsx(
    styles.ctaBlock,
    styles[align as keyof typeof styles],
  );

  const ctaButtonClasses = clsx(
    stylesCta.callToAction,
    stylesCta.buttonPrimary,
    styles.button,
  );

  // - Colors
  const isTransparent = bgColor?.alpha === 0;
  const bgColorHex = isTransparent ? "transparent" : bgColor?.hex ?? "#000";
  const colors = {
    bg: bgColorHex,
    bgHover: isTransparent ? "transparent" : brightness(bgColorHex, 30),
    text:
      !colorAuto && color
        ? color?.hex
        : getContrastYIQ(bgColorHex)
          ? "#000"
          : "#fff",
  };
  //console.log( colorAuto, color?.hex, bgColorHex, getContrastYIQ(bgColorHex) );

  return (
    <m.div ref={ctaRef} className={ctaClasses}>
      {title && <div className={styles.title}>{title}</div>}

      <CallToAction
        key={`cta-${id}`}
        href={ctaLink}
        variant="buttonPrimary"
        target={newtab ? "_blank" : "_self"}
        className={ctaButtonClasses}
        style={
          {
            "--bg-color": colors.bg,
            "--bg-color-hover": colors.bgHover,
            "--color": colors.text,
            "--image": image ? `url(${image?.url})` : "none",
          } as CustomCSSProperties
        }
      >
        {buttonText}
      </CallToAction>
    </m.div>
  );
}
