/**
 * Hook for getting the current tenant's currency configuration
 *
 * This hook provides:
 * - The currency code (EUR, USD, GBP)
 * - The currency symbol (€, $, £)
 * - A currency formatter function
 *
 * It reads from the current tenant's settings and defaults to EUR.
 */

import { useMemo } from 'react';
import { useCurrentTenant } from '../stores/tenant.store';
import {
  CURRENCY_CONFIG,
  DEFAULT_CURRENCY,
  getCurrencySymbol,
  formatCurrency,
  type CurrencyCode
} from '../utils/currency';

export interface TenantCurrencyInfo {
  /** Currency code (EUR, USD, GBP) */
  currencyCode: CurrencyCode;
  /** Currency symbol (€, $, £) */
  currencySymbol: string;
  /** Currency name (Euro, US Dollar, British Pound) */
  currencyName: string;
  /** Format a number as currency */
  format: (amount: number) => string;
  /** Format a number as currency (compact format for large numbers) */
  formatCompact: (amount: number) => string;
}

/**
 * Hook to get the current tenant's currency configuration
 *
 * @returns TenantCurrencyInfo with currency code, symbol, and formatting functions
 *
 * @example
 * const { currencySymbol, format } = useTenantCurrency();
 *
 * // Display currency symbol in a label
 * <label>Costo Unitario ({currencySymbol})</label>
 *
 * // Format a value
 * <span>{format(123.45)}</span> // "123,45 €"
 */
export function useTenantCurrency(): TenantCurrencyInfo {
  const currentTenant = useCurrentTenant();

  return useMemo(() => {
    // Get currency from tenant, default to EUR
    const tenantCurrency = currentTenant?.currency;
    const currencyCode: CurrencyCode =
      (tenantCurrency && tenantCurrency in CURRENCY_CONFIG)
        ? (tenantCurrency as CurrencyCode)
        : DEFAULT_CURRENCY;

    const config = CURRENCY_CONFIG[currencyCode];

    return {
      currencyCode,
      currencySymbol: getCurrencySymbol(currencyCode),
      currencyName: config.name,
      format: (amount: number) => formatCurrency(amount, currencyCode),
      formatCompact: (amount: number) => {
        // Compact format for large numbers (e.g., €1.2K, €1.5M)
        if (amount >= 1000000) {
          return `${config.symbol}${(amount / 1000000).toFixed(1)}M`;
        } else if (amount >= 1000) {
          return `${config.symbol}${(amount / 1000).toFixed(1)}K`;
        }
        return formatCurrency(amount, currencyCode);
      },
    };
  }, [currentTenant?.currency]);
}

/**
 * Get currency symbol without hook (for use in non-component code)
 * Falls back to EUR symbol (€)
 */
export function getTenantCurrencySymbol(tenantCurrency?: string | null): string {
  const currencyCode: CurrencyCode =
    (tenantCurrency && tenantCurrency in CURRENCY_CONFIG)
      ? (tenantCurrency as CurrencyCode)
      : DEFAULT_CURRENCY;
  return getCurrencySymbol(currencyCode);
}

export default useTenantCurrency;
