import React, { FC, useEffect, useState } from 'react';
import { camelCase } from 'lodash';

import {
  getCountriesWithFlagAsync,
  getCountriesListAsync,
  getFlagsAsync,
} from '~/utils/countriesList';
import { Select } from '~/components/Select';
import { Option } from './Option';

type flags = {
  [countryName: string]: string;
};

interface OptionType {
  value: string;
  label: React.ReactNode;
  isDisabled?: boolean;
}
type SelectProps = React.ComponentProps<typeof Select>;

export interface CountrySelectProps extends SelectProps {
  options?: OptionType[];
}

const getOptions = async (
  setOptions: React.Dispatch<React.SetStateAction<OptionType[]>>,
  props: CountrySelectProps
) => {
  const flags: flags = await getFlagsAsync();
  const countriesList = await getCountriesListAsync();
  const countriesWithFlag = await getCountriesWithFlagAsync();

  const options: OptionType[] = Object.keys(countriesWithFlag).map(
    (countryCode) => {
      const option: OptionType = {
        value: countryCode,
        label: (
          <Option
            icon={
              <img
                src={flags[camelCase(countriesWithFlag[countryCode])]}
                width={25}
                height={25}
              />
            }
            label={countriesList[countryCode]}
          />
        ),
      };

      if (
        props.disabledOptions &&
        props.disabledOptions.indexOf(countryCode) !== -1
      ) {
        option.isDisabled = true;
      }

      return option;
    }
  );

  setOptions(options);
};

export const CountrySelect: FC<CountrySelectProps> = ({
  options: optionsProp = [],
  ...otherProps
}) => {
  const [options, setOptions] = useState(optionsProp);

  useEffect(() => {
    if (!options.length) {
      getOptions(setOptions, otherProps);
    }
  }, [options.length, otherProps]);

  return (
    <Select
      options={options}
      isDisabled={!options.length}
      noIcon
      {...otherProps}
    />
  );
};
