import React, { FC, useState } from 'react';
import { useMutation } from '@apollo/react-hooks';
import { SelectInput } from '@orchard/frontend-react-components';
import { SetCountryFilter } from 'src/definitions/SetCountryFilter';
import SET_COUNTRY_FILTER from 'src/mutations/setCountryFilter.gql';
import { useComparisonFilters } from 'src/queries';
import { COUNTRY_ITEMS, WORLDWIDE } from 'src/constants/countries';
import { getCountryName } from 'src/selectors/filters';


const CountryFilter: FC<{ className: string }> = ({ className }) => {
    const { selectedSongIds, countryFilter } = useComparisonFilters();
    const [setCountryFilter] = useMutation<SetCountryFilter>(SET_COUNTRY_FILTER);
    const [selectedCountry, setSelectedCountry] = useState<string>(
        countryFilter.length ? countryFilter[0] : WORLDWIDE
    );

    const handleCountrySelection = (val: string) => {
        setSelectedCountry(val || WORLDWIDE);
        setCountryFilter({ variables: { countries: val === WORLDWIDE ? [] : [val] } });
    };

    const selectValue = countryFilter.length === 0 ? WORLDWIDE : countryFilter[0];
    const countryOptions = [
        { label: getCountryName(WORLDWIDE), value: WORLDWIDE },
        ...COUNTRY_ITEMS
    ];

    return (
        <div className={`${className}-filter ${className}-country`}>
            <SelectInput
                disabled={selectedSongIds.length === 0}
                clearable={selectedCountry !== WORLDWIDE}
                onChange={handleCountrySelection}
                options={countryOptions}
                value={selectValue}
            />
        </div>
    );
};

export default CountryFilter;
