import { useCallback } from 'react';

import type { FC } from 'react';
import type { PickerProps } from './Picker';

import { COUNTRY_COOKIE_NAME } from '~/lib/constants';
import { setClientCookie } from '~/lib/utils/cookie';
import FadeOnMount from '~/src/components/FadeOnMount';
import countriesByCode, {
  getCountryName,
} from '~/src/lib/utils/countriesByCode';
import { useSelector } from '~/src/store/redux';
import { selectUserCountry } from '~/src/store/session/selectors';
import Picker from './Picker';

const selectItems = Object.keys(countriesByCode).map((code) => ({
  id: code,
  text: countriesByCode[code],
}));

export const CountryPicker: FC<Pick<PickerProps, 'height' | 'margin'>> = (
  pickerProps
) => {
  const country = useSelector(selectUserCountry);

  // just in-case we get fed a country-code that's not in the list fallback to US
  const countryName = getCountryName(country) || getCountryName('US');

  const onCountryChange = useCallback((country) => {
    setClientCookie(COUNTRY_COOKIE_NAME, country);
    window.location.reload();
  }, []);

  return (
    <FadeOnMount>
      <Picker
        {...pickerProps}
        onChange={onCountryChange}
        title="Change country"
        value={country}
        items={selectItems}
        currentText={countryName}
        testId="countryPicker"
      />
    </FadeOnMount>
  );
};
