import { useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { formatCurrency, formatNumber, parseCurrencyValue, getCurrencyByCode } from '../config/currencies';

/**
 * Hook personalizado para formatação de valores monetários e números
 * com suporte a internacionalização
 */
export const useFormatters = () => {
  const { i18n } = useTranslation();
  
  /**
   * Formata valor como moeda
   */
  const currency = useCallback((value, currencyCode = 'BRL') => {
    return formatCurrency(value, currencyCode);
  }, []);

  /**
   * Formata apenas número sem símbolo de moeda
   */
  const number = useCallback((value, currencyCode = 'BRL') => {
    return formatNumber(value, currencyCode);
  }, []);

  /**
   * Converte string formatada para número
   */
  const parseValue = useCallback((formattedValue) => {
    return parseCurrencyValue(formattedValue);
  }, []);

  /**
   * Formata data de acordo com o idioma atual
   */
  const date = useCallback((dateValue, options = {}) => {
    if (!dateValue) return '';
    
    const date = dateValue instanceof Date ? dateValue : new Date(dateValue);
    const locale = i18n.language === 'pt-BR' ? 'pt-BR' : 
                   i18n.language === 'en' ? 'en-US' : 'es-ES';
    
    const defaultOptions = {
      day: '2-digit',
      month: '2-digit',
      year: 'numeric',
    };

    try {
      return new Intl.DateTimeFormat(locale, { ...defaultOptions, ...options }).format(date);
    } catch (error) {
      return date.toLocaleDateString();
    }
  }, [i18n.language]);

  /**
   * Formata data e hora
   */
  const dateTime = useCallback((dateValue, options = {}) => {
    if (!dateValue) return '';
    
    const date = dateValue instanceof Date ? dateValue : new Date(dateValue);
    const locale = i18n.language === 'pt-BR' ? 'pt-BR' : 
                   i18n.language === 'en' ? 'en-US' : 'es-ES';
    
    const defaultOptions = {
      day: '2-digit',
      month: '2-digit',
      year: 'numeric',
      hour: '2-digit',
      minute: '2-digit',
    };

    try {
      return new Intl.DateTimeFormat(locale, { ...defaultOptions, ...options }).format(date);
    } catch (error) {
      return date.toLocaleString();
    }
  }, [i18n.language]);

  /**
   * Formata data relativa (há 2 dias, em 3 horas, etc)
   */
  const relativeTime = useCallback((dateValue) => {
    if (!dateValue) return '';
    
    const date = dateValue instanceof Date ? dateValue : new Date(dateValue);
    const now = new Date();
    const diffMs = date - now;
    const diffSecs = Math.round(diffMs / 1000);
    const diffMins = Math.round(diffSecs / 60);
    const diffHours = Math.round(diffMins / 60);
    const diffDays = Math.round(diffHours / 24);

    const locale = i18n.language === 'pt-BR' ? 'pt-BR' : 
                   i18n.language === 'en' ? 'en-US' : 'es-ES';

    try {
      const rtf = new Intl.RelativeTimeFormat(locale, { numeric: 'auto' });
      
      if (Math.abs(diffDays) >= 1) {
        return rtf.format(diffDays, 'day');
      } else if (Math.abs(diffHours) >= 1) {
        return rtf.format(diffHours, 'hour');
      } else if (Math.abs(diffMins) >= 1) {
        return rtf.format(diffMins, 'minute');
      } else {
        return rtf.format(diffSecs, 'second');
      }
    } catch (error) {
      return date.toLocaleDateString();
    }
  }, [i18n.language]);

  /**
   * Formata porcentagem
   */
  const percent = useCallback((value, decimals = 1) => {
    const locale = i18n.language === 'pt-BR' ? 'pt-BR' : 
                   i18n.language === 'en' ? 'en-US' : 'es-ES';
    
    try {
      return new Intl.NumberFormat(locale, {
        style: 'percent',
        minimumFractionDigits: decimals,
        maximumFractionDigits: decimals,
      }).format(value / 100);
    } catch (error) {
      return `${value.toFixed(decimals)}%`;
    }
  }, [i18n.language]);

  /**
   * Obtém informações da moeda
   */
  const getCurrency = useCallback((code) => {
    return getCurrencyByCode(code);
  }, []);

  return {
    currency,
    number,
    parseValue,
    date,
    dateTime,
    relativeTime,
    percent,
    getCurrency,
  };
};

export default useFormatters;
