import React, { useMemo } from 'react';
import PropTypes from 'prop-types';
import Select, { components, createFilter } from 'react-select';
import { Controller } from 'react-hook-form';
import { createNamespace } from '../../tools/namingTools';
import { SMALL } from '../../constants/sizes';
import { LIGHT, DARK } from '../../constants/themeColor';
import FormLabel from '../form-label/FormLabel';
// IMPORTANT: (s)css should be imported after other atoms/components
import './styles/Select.scss';

const n = createNamespace('Select');

// These two inner components receive props dictated by react-select's internal
// API, not by consumers, so prop-types validation is not applicable here.
/* eslint-disable react/prop-types */
const createAccessibleSelectComponents = listboxId => ({
    Input: ({ selectProps, ...inputProps }) => (
        <components.Input
            {...inputProps}
            selectProps={selectProps}
            role="combobox"
            aria-haspopup="listbox"
            aria-expanded={selectProps.menuIsOpen}
            aria-controls={listboxId || undefined}
        />
    ),
    MenuList: ({ innerProps, ...menuListProps }) => (
        <components.MenuList
            {...menuListProps}
            innerProps={{
                ...innerProps,
                ...(listboxId ? { id: listboxId, role: 'listbox' } : {})
            }}
        />
    )
});
/* eslint-enable react/prop-types */

const SpecificSelect = ({
    name,
    value,
    label,
    size,
    theme,
    type,
    width,
    defaultValue,
    options,
    placeholder,
    hiddenLabel,
    onChange,
    isSearchable,
    withBackground,
    classNamePrefix,
    inline,
    hookFormControl,
    validationRules,
    error,
    required,
    i18n
}) => {
    const prefix = classNamePrefix || 'select';
    const customStyles = {
        control: () => ({
            width: width || '100%'
        })
    };
    const valueShape = options && options.find(o => o.value === value);
    const inlineClass = 'inline';
    const labelTextModifier = [
        hiddenLabel ? 'hidden' : null,
        inline && inlineClass
    ];
    const groupModifiers = [
        size,
        theme,
        type,
        error && 'error',
        !withBackground && 'transparent'
    ];

    // a11y: expose combobox semantics on the focusable input. react-select v4's
    // DummyInput (used when isSearchable=false) does not emit them, so we always
    // route through the Input component and lock inputValue when search is off.
    const listboxId = name ? `${name}-listbox` : undefined;
    const accessibleComponents = useMemo(
        () => createAccessibleSelectComponents(listboxId),
        [listboxId]
    );

    const inputProps = {
        inputId: name,
        instanceId: name,
        name,
        value: valueShape,
        options,
        styles: customStyles,
        placeholder,
        // Always true so custom Input can stamp aria-expanded from selectProps.menuIsOpen
        // during the same render that opens/closes the menu.
        isSearchable: true,
        menuPlacement: 'auto',
        className: `${prefix}__container`,
        onChange,
        classNamePrefix: prefix,
        components: accessibleComponents,
        listboxId,
        'aria-label': label || undefined,
        ...(!isSearchable && {
            inputValue: '',
            onInputChange: () => {}
        })
    };

    if (isSearchable) {
        inputProps.filterOption = createFilter({
            ignoreCase: true,
            ignoreAccents: true,
            trim: true,
            matchFrom: 'start'
        });
    }

    let input;
    if (hookFormControl) {
        input = (
            <Controller
                control={hookFormControl}
                name={name}
                value={valueShape}
                defaultValue={defaultValue || ''}
                render={({ onChange: innerOnChange, onBlur: innerOnBlur, value: innerValue, name: innerName }) => (
                    <Select
                        {...inputProps}
                        onChange={v => {
                            if (onChange) {
                                onChange(v);
                            }
                            innerOnChange(v);
                        }}
                        onBlur={innerOnBlur}
                        value={innerValue}
                        name={innerName}
                    />
                )}
                rules={validationRules}
            />
        );
    } else {
        input = <Select {...inputProps} />;
    }

    return (
        <div {...n('group', groupModifiers).withTestId().props}>
            <FormLabel
                labelText={label}
                required={required}
                labelProps={n('label', inline && inlineClass).withE2EId().withTestId().props}
                textProps={n('text', labelTextModifier).props}
                htmlFor={name}
                i18n={i18n}
            >
                {input}
            </FormLabel>
            {error && (
                <span {...n('error').props} aria-live="assertive">
                    {error}
                </span>
            )}
        </div>
    );
};

const selectOptionShape = {
    label: PropTypes.string,
    value: PropTypes.string
};

SpecificSelect.propTypes = {
    name: PropTypes.string,
    label: PropTypes.string,
    value: PropTypes.string,
    type: PropTypes.oneOf(['button']),
    theme: PropTypes.oneOf([LIGHT.value, DARK.value]),
    size: PropTypes.oneOf([SMALL.value, 'auto']),
    width: PropTypes.number,
    defaultValue: PropTypes.oneOfType([
        PropTypes.string,
        PropTypes.shape(selectOptionShape)
    ]),
    classNamePrefix: PropTypes.string,
    options: PropTypes.arrayOf(PropTypes.shape(selectOptionShape)),
    placeholder: PropTypes.string,
    hiddenLabel: PropTypes.bool,
    isSearchable: PropTypes.bool,
    withBackground: PropTypes.bool,
    inline: PropTypes.bool,
    error: PropTypes.string,
    hookFormControl: PropTypes.object,
    validationRules: PropTypes.object,
    onChange: PropTypes.func,
    required: PropTypes.bool,
    i18n: PropTypes.shape({
        fieldRequired: PropTypes.string
    })
};

SpecificSelect.defaultProps = {
    name: null,
    label: null,
    value: undefined,
    type: null,
    theme: null,
    size: null,
    width: null,
    defaultValue: null,
    classNamePrefix: null,
    options: [],
    placeholder: null,
    hiddenLabel: false,
    isSearchable: false,
    withBackground: true,
    inline: false,
    error: null,
    hookFormControl: null,
    validationRules: null,
    onChange: () => null,
    required: false,
    i18n: null
};

export default SpecificSelect;
