import { useFormContext } from 'react-hook-form';

import Box from '@material-hu/mui/Box';

import HuAutocomplete from '@material-hu/components/design-system/Inputs/Autocomplete';

import { useLokaliseTranslation } from 'src/utils/i18n';

import { countriesArray as countries, countriesObject } from 'src/constants';
import { type CountryType } from 'src/types/form';

import { useFormCreation } from '../../../contexts/FormCreation';
import { newServiceItemFields } from '../../../forms';

type CountryOption = {
  label: string;
  value: string;
};

const PhoneOptions = () => {
  const { t } = useLokaliseTranslation('service_management');
  const { t: tCountry } = useLokaliseTranslation('backoffice_only');
  const { selected } = useFormCreation();
  const { watch, setValue } = useFormContext();

  const defaultCountryCodeName =
    newServiceItemFields.form.sections.questions.defaultCountryCode(
      selected.section,
      selected.question,
    );

  const options: CountryOption[] = countries.map((c: CountryType) => ({
    label: `${tCountry(`backoffice_only:form_country_code.${c.code.toLowerCase()}`)} (+${c.phone})`,
    value: c.code,
  }));

  const watchedValue: string = watch(defaultCountryCodeName);
  const selectedOption =
    options.find(o => o.value === watchedValue) ?? options[0];

  return (
    <HuAutocomplete
      value={selectedOption}
      options={options}
      onChange={(option: CountryOption | null) => {
        if (option) setValue(defaultCountryCodeName, option.value);
      }}
      label={t('code')}
      noOptionsMessage={{ title: t('no_country_code_options') }}
      disableClearable
      isServerFiltered={false}
      renderOption={(
        props: React.HTMLAttributes<HTMLLIElement>,
        option: CountryOption,
      ) => {
        const country =
          countriesObject[option.value as keyof typeof countriesObject];

        return (
          <Box
            component="li"
            sx={{ '& > img': { mr: 2, flexShrink: 0 } }}
            {...props}
            key={option.value}
          >
            <img
              loading="lazy"
              width="20"
              srcSet={`https://flagcdn.com/w40/${country.code.toLowerCase()}.png 2x`}
              src={`https://flagcdn.com/w20/${country.code.toLowerCase()}.png`}
              alt=""
            />
            {option.label}
          </Box>
        );
      }}
    />
  );
};

export default PhoneOptions;
