import { useTranslation } from './useTranslation';
import {
  format as dateFnsFormat,
  formatDistanceToNow as dateFnsFormatDistanceToNow,
  formatDistance as dateFnsFormatDistance,
  formatRelative as dateFnsFormatRelative,
} from 'date-fns';
import { enUS, es, fr, ptBR, zhCN } from 'date-fns/locale';

/**
 * Map of i18next language codes to date-fns locales
 */
const localeMap: Record<string, Locale> = {
  'en': enUS,
  'en-US': enUS,
  'es': es,
  'es-ES': es,
  'fr': fr,
  'fr-FR': fr,
  'pt': ptBR,
  'pt-BR': ptBR,
  'zh': zhCN,
  'zh-CN': zhCN,
};

/**
 * Custom hook for localized date formatting using date-fns
 * Automatically applies the correct locale based on the current i18n language
 */
export function useLocalizedDate() {
  const { language } = useTranslation();

  // Get the locale for the current language, fallback to enUS
  const locale = localeMap[language] || enUS;

  /**
   * Format a date using date-fns with the current locale
   * @param date - The date to format
   * @param formatStr - The format string (e.g., 'PPP', 'MM/dd/yyyy')
   */
  const format = (date: Date | number | string, formatStr: string): string => {
    const dateObj = typeof date === 'string' ? new Date(date) : date;
    return dateFnsFormat(dateObj, formatStr, { locale });
  };

  /**
   * Format a date as a distance to now (e.g., "2 hours ago")
   * @param date - The date to format
   * @param options - Optional options for formatDistanceToNow
   */
  const formatDistanceToNow = (
    date: Date | number | string,
    options?: { addSuffix?: boolean; includeSeconds?: boolean }
  ): string => {
    const dateObj = typeof date === 'string' ? new Date(date) : date;
    return dateFnsFormatDistanceToNow(dateObj, { ...options, locale });
  };

  /**
   * Format the distance between two dates
   * @param date - The later date
   * @param baseDate - The earlier date
   * @param options - Optional options for formatDistance
   */
  const formatDistance = (
    date: Date | number,
    baseDate: Date | number,
    options?: { addSuffix?: boolean; includeSeconds?: boolean }
  ): string => {
    return dateFnsFormatDistance(date, baseDate, { ...options, locale });
  };

  /**
   * Format a date relative to now (e.g., "today at 5:00 PM")
   * @param date - The date to format
   * @param baseDate - Optional base date (defaults to now)
   */
  const formatRelative = (
    date: Date | number,
    baseDate?: Date | number
  ): string => {
    return dateFnsFormatRelative(date, baseDate || new Date(), { locale });
  };

  return {
    format,
    formatDistanceToNow,
    formatDistance,
    formatRelative,
    locale,
  };
}
