import { useEffect, useRef, useState } from "react";
import clsx from "clsx";
import { m, useAnimate } from "framer-motion";

import CallToAction from "@/components/call-to-action";

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

export interface QuizCallToActionProps {
  label?: string;
  ariaLabel?: string;
  onClick?: React.MouseEventHandler<HTMLButtonElement | HTMLAnchorElement>;
  disabled?: boolean;
}

export const QuizCallToAction = ({
  label,
  onClick,
  disabled,
}: QuizCallToActionProps) => {
  const textRef = useRef<HTMLDivElement>(null);
  const [scope, animate] = useAnimate();

  const [width, setWidth] = useState<number>(50);

  useEffect(() => {
    setWidth((textRef?.current?.offsetWidth || 50) + 26 * 2);
  }, [label, textRef]);

  function onFocusHandler(
    e: React.FocusEvent<HTMLButtonElement | HTMLAnchorElement>,
  ) {}

  return (
    <div
      ref={scope}
      id="wrapper"
      className={clsx(styles.wrapper, {
        [styles.disabled]: disabled,
      })}
    >
      <m.div
        className={styles.background}
        animate={{ width: width }}
        transition={{
          type: "spring",
          damping: 10,
          bounce: 0.6,
          stiffness: 100,
          mass: 0.9,
        }}
      ></m.div>

      <CallToAction
        variant="buttonPill"
        tabIndex={0}
        className={clsx(styles.quizCallToAction, {
          [styles.disabled]: disabled,
        })}
        onClick={onClick}
        onFocus={onFocusHandler}
      >
        <span key="" id="label" ref={textRef} className={styles.span}>
          {label}
        </span>
      </CallToAction>
    </div>
  );
};

export default QuizCallToAction;
