import { removeAfterDot, roundToWhole } from "@/services/price";
import styles from "./styles.module.css";
import Price, { Currency, Locale } from "@/components/PaymentTable/Price";
import { useEffect, useRef } from "react";
import { useDispatch } from "react-redux";
import { actions } from "@/store";

interface PriceItemProps {
  id: string;
  value: number;
  active: boolean;
  className?: string;
  classNameActive?: string;
  currency: Currency;
  click: (id: string) => void;
}

function PriceItem({
  id,
  value,
  active,
  className = "",
  classNameActive = "",
  currency = Currency.USD,
  click,
}: PriceItemProps): JSX.Element {
  const dispatch = useDispatch();
  const locale = Locale.EN;

  const _price = new Price(
    roundToWhole(value),
    currency,
    locale
  );

  const itemRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (value === 13.76 && itemRef.current?.offsetLeft) {
      dispatch(
        actions.siteConfig.updateTrialChoiceArrowOptions({
          left: `${
            itemRef.current.offsetLeft + itemRef.current.offsetWidth / 2 - 26
          }px`,
        })
      );
    }
  }, [dispatch, value, itemRef.current?.offsetLeft]);

  const compatClassName = () => {
    // const isPopular = id === "stripe.7";
    const isPopular = false;
    const isActive = active;
    return `${styles.container} ${isPopular ? styles.popular : ""} ${
      isActive ? `${styles.active} ${classNameActive}` : ""
    } ${className}`;
  };

  const itemClick = () => {
    click(id);
  };

  return (
    <div
      ref={value === 13.76 ? itemRef : null}
      onClick={itemClick}
      className={compatClassName()}
    >
      {removeAfterDot(_price.format())}
    </div>
  );
}

export default PriceItem;
