/* https://github.com/mayank8aug/use-localization/blob/main/src/index.ts */

import { IMoney, IPercentage, IQuantity } from "@/lib/types";
import { adjustPrecision } from "@shared/utilities/helpers";
import { useCallback } from "react";
import { useTranslation } from "react-i18next";

type UseLocalizationProps = {
  locale?: string;
};

export const useLocalization = () => {
  const { i18n } = useTranslation();

  return useCustomLocalization({
    locale: i18n.language,
  });
};

export const useCustomLocalization = (props: UseLocalizationProps) => {
  const { locale } = props;

  const formatCurrency = useCallback(
    (value: IMoney | null) => {
      if (value === null || value === undefined) {
        return "";
      }

      const { amount, scale, currency_code } = value;

      return new Intl.NumberFormat(locale ?? "ES", {
        style: "currency",
        currency: currency_code,
        currencyDisplay: "symbol",
        useGrouping: true,

        maximumFractionDigits: scale,
      }).format(amount === null ? 0 : adjustPrecision({ amount, scale }));
    },
    [locale]
  );

  const formatNumber = useCallback(
    (value: IMoney | IPercentage | IQuantity | null) => {
      if (value === null || value === undefined) {
        return "";
      }

      const { amount, scale } = value;

      const result = new Intl.NumberFormat("es", {
        /*minimumSignificantDigits: scale,
        maximumSignificantDigits: scale,*/
        minimumFractionDigits: scale,
        useGrouping: true,
      }).format(amount === null ? 0 : adjustPrecision({ amount, scale }));

      //console.log(value, result);

      return result;
    },
    [locale]
  );

  const formatPercentage = useCallback(
    (value: IPercentage | null) => {
      if (value === null || value === undefined) {
        return "";
      }

      const { amount, scale } = value;

      return new Intl.NumberFormat(locale, {
        style: "decimal",
        minimumFractionDigits: scale,
      }).format(amount === null ? 0 : amount);
    },
    [locale]
  );

  return {
    formatCurrency,
    formatNumber,
    formatPercentage,
  };
};
