import type { MoneyDTO } from "@erp/core/common";
import type { Currency } from "dinero.js";
import * as React from "react";
import { useTranslation } from "../i18n";

/**
 * Hook para manipular valores MoneyDTO con operaciones,
 * formato, parseo y conversión seguras.
 */
export function useMoneyDTO(overrides?: {
  locale?: string;
  fallbackCurrency?: Currency;
  defaultScale?: number;
}) {
  const { i18n } = useTranslation();
  const locale = overrides?.locale || i18n.language || "es-ES";
  const fallbackCurrency: Currency = overrides?.fallbackCurrency ?? "EUR";
  const defaultScale = overrides?.defaultScale ?? 2;

  // Conversión
  const toNumber = React.useCallback(
    (dto?: MoneyDTO | null) => toNumberUnsafe(dto, defaultScale),
    [defaultScale]
  );

  const fromNumber = React.useCallback(
    (n: number, currency: Currency = fallbackCurrency, scale: number = defaultScale): MoneyDTO =>
      fromNumberUnsafe(n, currency, scale),
    [fallbackCurrency, defaultScale]
  );

  // Operaciones
  const add = React.useCallback(
    (a: MoneyDTO, b: MoneyDTO): MoneyDTO => sumDTO([a, b], fallbackCurrency),
    [fallbackCurrency]
  );

  const sub = React.useCallback(
    (a: MoneyDTO, b: MoneyDTO): MoneyDTO => sumDTO([a, multiplyDTO(b, -1)], fallbackCurrency),
    [fallbackCurrency]
  );

  const multiply = React.useCallback(
    (dto: MoneyDTO, k: number, rounding: Dinero.RoundingMode = "HALF_EVEN") =>
      multiplyDTO(dto, k, rounding, fallbackCurrency),
    [fallbackCurrency]
  );

  const percentage = React.useCallback(
    (dto: MoneyDTO, p: number, rounding: Dinero.RoundingMode = "HALF_EVEN") =>
      percentageDTO(dto, p, rounding, fallbackCurrency),
    [fallbackCurrency]
  );

  // Formatos
  const formatCurrency = React.useCallback(
    (dto: MoneyDTO, loc?: string) => formatDTO(dto, loc ?? locale),
    [locale]
  );

  const parse = React.useCallback((text: string): number | null => parseLocaleNumber(text), []);

  // Estado
  const isZero = React.useCallback((dto?: MoneyDTO | null) => toNumber(dto) === 0, [toNumber]);

  return React.useMemo(
    () => ({
      toNumber,
      fromNumber,
      add,
      sub,
      multiply,
      percentage,
      formatCurrency,
      parse,
      isZero,
      roundToScale,
      stepNumber,
      stripCurrencySymbols,
      toDinero: (dto: MoneyDTO) => dineroFromDTO(dto, fallbackCurrency),
      fromDinero: dtoFromDinero,
      locale,
      fallbackCurrency,
      defaultScale,
    }),
    [
      toNumber,
      fromNumber,
      add,
      sub,
      multiply,
      percentage,
      formatCurrency,
      parse,
      isZero,
      fallbackCurrency,
      locale,
      defaultScale,
    ]
  );
}
