import React, { useMemo } from "react";

import { useSelector } from "react-redux";

import { parseLocalizedNumber } from "../utils/helperMethods";

const priceInfoKeys = [
  "originalPrice",
  "discountedPrice",
  "rewardFlag",
  "discountAmount",
  "discountRate",
  "promotionCode",
  "promotionDate",
];

export default function usePriceInfo(priceInfo) {
  const countryCode = useSelector((state) => state.common.httpHeader.cntry_cd);

  const parsedPriceInfo = useMemo(() => {
    if (!priceInfo) {
      return;
    }

    const splittedPriceInfo = priceInfo.split("|").map((item) => item.trim());

    const processedPriceInfo = priceInfoKeys.reduce((objcet, key, index) => {
      objcet[key] = splittedPriceInfo[index];
      return objcet;
    }, {});

    let {
      originalPrice,
      discountedPrice,
      rewardFlag,
      discountAmount,
      discountRate,
      promotionCode,
      promotionDate,
    } = processedPriceInfo;

    const originalPriceNum = parseLocalizedNumber(originalPrice, countryCode);
    const discountedPriceNum = parseLocalizedNumber(
      discountedPrice,
      countryCode
    );
    let discountRateNumeric = parseFloat(discountRate.replace("%", ""));

    if (discountedPriceNum >= originalPriceNum) {
      originalPrice = discountedPrice;
      discountRateNumeric = null;
      discountRate = null;
    }

    return {
      originalPrice,
      discountedPrice,
      rewardFlag,
      discountAmount,
      discountRate,
      discountRateNumeric,
      promotionCode,
      promotionDate,
    };
  }, [priceInfo]);

  return parsedPriceInfo;
}
