import { forwardRef, useMemo } from 'react';
import { getCountries } from '@theorchard/countries';

export type CountriesSelectProps =
    React.SelectHTMLAttributes<HTMLSelectElement> & {
        lang?: string;
        placeholder?: string;
    };

export const CountriesSelect = forwardRef<
    HTMLSelectElement,
    CountriesSelectProps
>(function CountriesSelect(
    { placeholder, ...props }: CountriesSelectProps,
    ref
) {
    const countries = useMemo(
        () => getCountries({ includeGlobal: false, locale: props.lang }),
        [props.lang]
    );

    return (
        <select defaultValue="" {...props} ref={ref}>
            {placeholder && <option value="">{placeholder}</option>}

            {countries.map(country => {
                return (
                    <option value={country.value} key={country.value}>
                        {country.label}
                    </option>
                );
            })}
        </select>
    );
});
