import React from 'react';
import { CountryFlag } from '@theorchard/suite-icons';
import { groupBy } from 'lodash';
import type { RestrictionLevel } from 'src/components/deliveryRestrictionsContext/types';

export const formatCountriesOptions = (
    countries: {
        continent: string;
        countryName: string | null;
        territoryName: string | null;
        territoryCodeA2: string;
        restrictedAtLevel?: RestrictionLevel[];
    }[],
    excludedCodes: string[] = []
) => {
    const countriesByContinent = groupBy(countries, 'continent');

    return Object.entries(countriesByContinent).map(
        ([continent, countryList]) => ({
            label: continent,
            value: continent,
            options: countryList
                .filter(
                    country => !excludedCodes.includes(country.territoryCodeA2)
                )
                .map(country => ({
                    label: country.territoryName,
                    value: country.territoryCodeA2,
                    icon: <CountryFlag countryCode={country.territoryCodeA2} />,
                    levels: country.restrictedAtLevel ?? [],
                })),
        })
    );
};
