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

interface PriceListProps {
  subPlans: ISubscriptionPlan[];
  activeItem: number | null;
  click: () => void;
}

const getPrice = (plan: ISubscriptionPlan) => {
  return (plan.trial?.price_cents || 0) / 100;
};

function PriceList({ click, subPlans }: PriceListProps): JSX.Element {
  const dispatch = useDispatch();
  const [activePlanItem, setActivePlanItem] =
    useState<ISubscriptionPlan | null>(null);

  const priceItemClick = (id: string) => {
    const activePlan = subPlans.find((item) => item.id === String(id)) || null;
    setActivePlanItem(activePlan);
    if (activePlan) {
      dispatch(
        actions.payment.update({
          activeSubPlan: activePlan,
        })
      );
    }
    setTimeout(() => {
      click();
    }, 1000);
  };

  return (
    <div className={`${styles.container}`}>
      {subPlans.map((plan, idx) => (
        <PriceItem
          active={plan.id === activePlanItem?.id}
          key={idx}
          value={getPrice(plan)}
          id={plan.id}
          click={priceItemClick}
        />
      ))}
    </div>
  );
}

export default PriceList;
