import { useLocation, useNavigate } from 'react-router-dom';

import type { L10nConfig } from '../types/hooks';

import { useThemeHooks } from './use-theme-hooks';
import {
  addLeadingSlash,
  getPathnameForLocale,
  withoutPathPrefix,
  withPathPrefix,
} from '../utils/urls';

export type UseLanguagePickerResult = {
  currentLocale: L10nConfig['locales'][number] | undefined;
  locales: L10nConfig['locales'];
  getLocaleUrl: (value: string) => string;
  /**
   * @deprecated Use `getLocaleUrl` to build the URL for the target locale, then pass it to `<Link>`.
   */
  setLocale: (value: string) => void;
};

export function useLanguagePicker(): UseLanguagePickerResult {
  const { useL10nConfig, useLoadAndNavigate } = useThemeHooks();
  const navigate = useNavigate();
  const loadAndNavigate = useLoadAndNavigate();

  const { currentLocale, locales, defaultLocale } = useL10nConfig();
  const location = useLocation();

  const locale = locales.find((l) => l.code === currentLocale);

  function getLocaleUrl(value: string): string {
    let newLangPathname = getPathnameForLocale(
      withoutPathPrefix(location.pathname),
      defaultLocale,
      value,
      locales,
    );

    if (location.search) {
      newLangPathname += location.search;
    }

    return addLeadingSlash(newLangPathname);
  }

  function setLocale(value: string): void {
    const newUrlWithLanguage = withPathPrefix(getLocaleUrl(value));
    loadAndNavigate({ navigate, to: newUrlWithLanguage });
  }

  return {
    currentLocale: locale,
    locales,
    getLocaleUrl,
    setLocale,
  };
}
