import { useState } from "react";
import PriceItem from "../PriceItem";
import styles from "./styles.module.css";
import { useDispatch } from "react-redux";
import { actions } from "@/store";
import { IFunnelPaymentVariant } from "@/api/resources/Session";

interface PriceListProps {
  products: IFunnelPaymentVariant[];
  activeItem: number | null;
  classNameItem?: string;
  classNameItemActive?: string;
  click: () => void;
}

const getPrice = (product: IFunnelPaymentVariant) => {
  return (product.trialPrice || 0) / 100;
};

function PriceList({
  click,
  products,
  classNameItem = "",
  classNameItemActive = "",
}: PriceListProps): JSX.Element {
  const dispatch = useDispatch();
  const [activeProduct, setActiveProduct] = useState<IFunnelPaymentVariant | null>(
    null
  );

  const priceItemClick = (id: string) => {
    const activeProduct =
      products.find((item) => item.id === String(id)) || null;
    setActiveProduct(activeProduct);
    if (activeProduct) {
      dispatch(
        actions.payment.update({
          activeProduct,
        })
      );
    }
    click();
  };

  return (
    <div className={`${styles.container}`}>
      {products.map((product, idx) => (
        <PriceItem
          active={product.id === activeProduct?.id}
          key={idx}
          value={getPrice(product)}
          id={product.id}
          className={classNameItem}
          classNameActive={classNameItemActive}
          click={priceItemClick}
        />
      ))}
    </div>
  );
}

export default PriceList;
