import { useCallback, useMemo, useSyncExternalStore } from 'react';
import { useAppContext } from './useAppContext.js';
import { useBchToFiatRate } from './useRates.js';

/**
 * Reactive BCH satoshis -> fiat conversion helpers for TUI screens.
 *
 * This hook subscribes to rate updates through `useBchToFiatRate`, so any
 * component using it will re-render automatically when the selected pair
 * receives a new quote.
 */
export function useSatoshisConversion(targetCurrency?: string) {
  const { appService } = useAppContext();
  const subscribeToCurrency = useCallback(
    (callback: () => void) => {
      if (!appService || targetCurrency) {
        return () => {};
      }

      return appService.settings.on('settings-updated', (event) => {
        if (event.key === 'currency') {
          callback();
        }
      });
    },
    [appService, targetCurrency],
  );

  const getCurrencySnapshot = useCallback(() => {
    if (targetCurrency) {
      return targetCurrency.toUpperCase();
    }

    if (!appService) {
      return 'USD';
    }

    return appService.settings.getCurrency();
  }, [appService, targetCurrency]);

  const currencyCode = useSyncExternalStore(
    subscribeToCurrency,
    getCurrencySnapshot,
    getCurrencySnapshot,
  );
  const fiatPerBchRate = useBchToFiatRate(currencyCode);

  const formattedFiatPerBchRate = useMemo(() => {
    if (!appService || fiatPerBchRate === null) {
      return null;
    }

    return appService.rates.formatCurrency(fiatPerBchRate, currencyCode);
  }, [appService, fiatPerBchRate, currencyCode]);

  const formatSatoshisToFiat = useCallback(
    (satoshis: bigint): string | null => {
      if (!appService || fiatPerBchRate === null) {
        return null;
      }

      return appService.rates.formatBchToFiat(satoshis, currencyCode);
    },
    [appService, fiatPerBchRate, currencyCode],
  );

  return {
    currencyCode,
    fiatPerBchRate,
    formattedFiatPerBchRate,
    formatSatoshisToFiat,
  } as const;
}
