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

import Icon from "@/components/icon";
import { getCopy } from "@/config/copy";
import { wrap } from "@/helpers/math";
import { useStore } from "@/store";
import { type SunoSong } from "@/types";

import CallToAction, { type CallToActionProps } from "./call-to-action";

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

interface SongVersionButtonProps extends CallToActionProps {
  onClick: React.MouseEventHandler<HTMLButtonElement | HTMLAnchorElement>;
}

const SongVersionButton = ({
  className,
  tabIndex,
  onClick,
  ...props
}: SongVersionButtonProps) => {
  const songs = useStore.use.songs();
  const song = useStore.use.song();
  const version = useMemo(() => {
    const index = songs.findIndex((s: SunoSong) => s.id === song.id);
    return ((songs.length - wrap(songs.length, index)) % songs.length) + 1;
  }, [song, songs]);

  const versionLabel = useMemo(() => {
    return getCopy("results:version");
  }, []);

  const ariaVersionLabel = useMemo(() => {
    const copy = getCopy("results:version_aria_label").replace(
      "[NUMBER]",
      version.toString(),
    );
    return copy.replace("[TOTAL NUMBER]", songs?.length.toString());
  }, [songs, version]);

  const animate = {
    scale: [0.95, 1],
    rotateX: [0, 360],
    transition: {
      type: "spring",
      duration: 1,
    },
  };

  const controls = useAnimationControls();
  return (
    <m.div animate={controls}>
      <CallToAction
        tabIndex={tabIndex}
        onClick={(event) => {
          onClick(event);
          controls.start(animate);
        }}
        variant="versionButton"
        ariaLabel={ariaVersionLabel}
      >
        <Icon className={styles.icon} variant="reload" />
        {versionLabel}
        <span className={styles.versionNumber}>{version}</span>
      </CallToAction>
    </m.div>
  );
};

export default SongVersionButton;
