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

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

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

function PriceList({
  click,
  products,
  classNameItem = "",
  classNameItemActive = "",
  classNamePricesContainer = "",
  preActiveItems = [],
  currency = Currency.USD,
}: PriceListProps): JSX.Element {
  const dispatch = useDispatch();
  const [activeProductItem, setActiveProductItem] = useState<IFunnelPaymentVariant>();

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

  return (
    <div className={`${styles.container} ${classNamePricesContainer}`}>
      {products.map((product, idx) => (
        <PriceItem
          active={
            product.id === activeProductItem?.id ||
            (preActiveItems.includes(product.id) && !activeProductItem)
          }
          key={idx}
          value={getPrice(product)}
          id={product.id}
          className={classNameItem}
          classNameActive={classNameItemActive}
          click={priceItemClick}
          currency={currency}
        />
      ))}
    </div>
  );
}

export default PriceList;
