import React from 'react';

import {Flex, Select, TextInput} from '@gravity-ui/uikit';
import block from 'bem-cn-lite';
import {I18n} from 'i18n';
import debounce from 'lodash/debounce';
import {Feature} from 'shared';
import type {UserRole} from 'shared/components/auth/constants/role';
import {registry} from 'ui/registry';
import {getUsersRoles} from 'ui/units/auth/utils/getUsersRoles';
import {getRoleByKey} from 'ui/units/auth/utils/userProfile';
import {isEnabledFeature} from 'ui/utils/isEnabledFeature';

import {BASE_USER_FILTERS} from '../constants';

import './UsersFilters.scss';

const b = block('service-settings-users-list-filters');
const i18n = I18n.keyset('service-settings.users-list.view');

const ROLES_OPTIONS = getUsersRoles().map((key) => ({
    value: key,
    content: getRoleByKey(key),
}));

const UPDATE_FILTERS_TIMEOUT = 500;

type UsersFilterProps = {
    onChange: (filterName: string, filterValue: string | string[] | undefined | null) => void;
};

export const UsersFilter = ({onChange}: UsersFilterProps) => {
    const [search, setSearch] = React.useState('');
    const [roles, setRole] = React.useState<UserRole[]>([]);

    const newServiceSettingsEnabled = isEnabledFeature(Feature.EnableNewServiceSettings);

    const {AdditionalUsersFilters} = registry.auth.components.getAll();

    const sendUpdatedFilters = React.useMemo(
        () => debounce((name, value) => onChange(name, value), UPDATE_FILTERS_TIMEOUT),
        [onChange],
    );

    const handleSearchChange = (value: string) => {
        setSearch(value);
        sendUpdatedFilters(BASE_USER_FILTERS.FILTER_STRING, value);
    };

    const handleRoleChange = (value: string[]) => {
        setRole(value as UserRole[]);
        sendUpdatedFilters(BASE_USER_FILTERS.ROLES, value);
    };

    return (
        <Flex className={b({new: newServiceSettingsEnabled})}>
            <TextInput
                value={search}
                onUpdate={handleSearchChange}
                hasClear={true}
                placeholder={i18n('label_search-placeholder')}
                className={b('search', {new: newServiceSettingsEnabled})}
                size={newServiceSettingsEnabled ? 'l' : 'm'}
            />
            <Select
                options={ROLES_OPTIONS}
                value={roles}
                hasClear={true}
                onUpdate={handleRoleChange}
                label={i18n('label_field-roles')}
                className={b('filter', {new: newServiceSettingsEnabled})}
                size={newServiceSettingsEnabled ? 'l' : 'm'}
            />
            <AdditionalUsersFilters
                onChange={onChange}
                className={b('filter', {new: newServiceSettingsEnabled})}
            />
        </Flex>
    );
};
