import { forwardRef } from "react";
import clsx from "clsx";
import {
  AnimatePresence,
  m,
  type MotionValue,
  useTransform,
} from "framer-motion";

import { AppCalloutCTA } from "@/components/call-to-action";
import { breakpoints } from "@/helpers/layout";
import type { PetalElement } from "@/types";

import { Dot } from "./dot";

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

interface Props extends PetalElement {
  xOffset?: number;
  yOffset?: number;
  width: number;
  height: number;
  scrollYProgress: MotionValue;
  isActive: boolean;
  isLast: boolean;
  isNotAllowed?: boolean;
  onClick: () => void;
  onViewportEnter: (entry: IntersectionObserverEntry | null) => void;
  onViewportLeave: (entry: IntersectionObserverEntry | null) => void;
}

export const Petal = forwardRef<HTMLDivElement, Props>(
  (
    {
      id,
      x,
      y,
      xOffset = 0,
      yOffset = 0,
      angle,
      width,
      height,
      label,
      scrollYProgress,
      isActive,
      isLast,
      isNotAllowed,
      onClick,
      onViewportEnter,
      onViewportLeave,
    },
    ref,
  ) => {
    const yParallax = useTransform(
      scrollYProgress,
      [0.5, 0.8, 1],
      width >= breakpoints.medium
        ? [y, y - height / 4, y - height / 2]
        : [y, y - height / 2, y - height],
    );
    const yParallaxLast = useTransform(
      scrollYProgress,
      [0.5, 0.6],
      [y, y - yOffset / 6],
    );

    const viewport = { margin: "-50% 0px -50% 0px" };

    if (isLast) {
      return (
        <m.div
          ref={ref}
          id={id}
          className={clsx(styles.petal, styles.appCallout)}
          style={{
            x: x,
            y: yParallaxLast,
            rotate: angle,
            width,
          }}
          viewport={viewport}
          onViewportEnter={onViewportEnter}
        >
          {/* <Image alt="Suno App" className={styles.icon} src={appLogo} /> */}
          <p className={styles.label}>{label}</p>
          <AppCalloutCTA className={styles.cta} context="lockup" />
        </m.div>
      );
    } else {
      return (
        <m.div
          ref={ref}
          id={id}
          className={clsx(styles.petal, {
            [styles.active]: isActive,
            [styles.notAllowed]: isNotAllowed && !isActive,
          })}
          style={{
            x: x + xOffset,
            y: yParallax,
            rotate: angle,
            width,
          }}
          onClick={() => {
            if (typeof onClick === "function") {
              onClick();
            }
          }}
          viewport={viewport}
          onViewportEnter={onViewportEnter}
          onViewportLeave={onViewportLeave}
          layout
        >
          <AnimatePresence>
            {isActive && !isNotAllowed && <Dot key={id} />}
          </AnimatePresence>
          <m.p className={styles.label} layout>
            {label}
          </m.p>
        </m.div>
      );
    }
  },
);
Petal.displayName = "Petal";
