import React from 'react';
import cn from 'classnames';
import { ReactComponent as ChevronDown } from "../../../assets/chevronDown.svg";
import { reverseBind } from "../../../utils";
import { FORM, POPUP_DIRECTION } from "../../../constants";
const { FORM_DISABLED_STATE } = FORM;
import { FormContext } from '../Form';
import { PopupContent, Trigger, Popup } from "../..";
import { AppDropdownComponent } from './AppDropdown';
import { DropdownWrapperDiv, DropdownLabelDiv, DropdownInputContentDiv, DropdownTriggerDiv, ChevronDownDiv, } from './styled';
const AppDropdownContent = React.forwardRef(AppDropdownComponent);
export class Select extends React.Component {
    constructor(props, context) {
        super(props);
        this.inputRef = React.createRef();
        this.optionsRef = React.createRef();
        this.onSelect = (value) => {
            const { props: { name, onSelect, withContext, onChange }, context: { onChange: onFormChange }, } = this;
            if (onChange) {
                onChange(value, name);
            }
            if (withContext && onFormChange) {
                onFormChange(name, value);
            }
            else if (onSelect)
                onSelect(value || '');
        };
        this.onEnterPress = (event) => {
            if (event.key === 'Enter') {
                this.inputRef.current.click();
            }
        };
        const { onSelect } = props;
        this.state = {
            isScrollable: false,
        };
        this.onSelect = onSelect ? reverseBind(onSelect, context) : this.onSelect.bind(this);
    }
    componentDidMount() {
        const { props } = this, { withContext } = props;
        this.makeScrollable();
        if (withContext) {
            const { context: { addField }, } = this;
            if (addField) {
                addField(props);
            }
        }
    }
    componentWillUnmount() {
        const { props } = this, { withContext, name } = props;
        if (withContext) {
            const { context: { deleteField }, } = this;
            if (deleteField) {
                deleteField(props.name);
            }
        }
    }
    componentDidUpdate({ value: prevValue }) {
        const { value, withContext, name } = this.props;
        if (value !== prevValue && withContext) {
            const { onChange } = this.context;
            if (onChange) {
                onChange(name, value);
            }
        }
    }
    makeScrollable() {
        const { maxHeight: { value: height }, focus, } = this.props;
        if (this.optionsRef.current && this.optionsRef.current.offsetHeight >= height) {
            this.setState({
                isScrollable: true,
            }, () => {
                const focusElement = document.getElementById(`#${focus || ''}`);
                if (focusElement) {
                    const { offsetTop } = focusElement;
                    this.optionsRef.current.scrollTop = offsetTop;
                    focusElement.classList.add('appForm-dropdownItem-isFocus');
                    focusElement.onmouseover = function onmouseover() {
                        focusElement.classList.remove('appForm-dropdownItem-isFocus');
                    };
                }
            });
        }
    }
    render() {
        const { props: { label, name, list, maxHeight: { value: heightVal, unit: heightUnit }, placeholder = '', value, withContext, hideSelected, tabIndex, disabled, uniqueFields, direction, centered = false, activeValueStyle, dropdownStyle, className, }, state: { isScrollable }, } = this;
        let currentValue = value, error = '';
        if (withContext) {
            const { fields } = this.context;
            currentValue = fields[name] ? fields[name].value : '';
            error = !fields[name] ? '' : fields[name].validation.errorMessage;
        }
        let isDisabled = disabled;
        if (withContext) {
            const { context: { disabled: formDisable }, } = this;
            isDisabled = disabled || formDisable === FORM_DISABLED_STATE.FORM;
        }
        const currentItem = list.find((item) => item.id === currentValue), optionsClassList = cn('appForm-dropdownList', {
            'appForm-dropdownList--scrollable': isScrollable,
        });
        const formattedList = hideSelected ? list.filter(({ id }) => currentValue !== id) : list;
        const PopupContainer = PopupContent;
        return (React.createElement(DropdownWrapperDiv, { className: className },
            label && React.createElement(DropdownLabelDiv, null, label),
            React.createElement("div", { onClickCapture: (e) => isDisabled && e.stopPropagation() },
                React.createElement(Popup, { behavior: "click", position: { direction: direction || POPUP_DIRECTION.BOTTOM_LEFT, centered } },
                    React.createElement(Trigger, { width: "100%" },
                        React.createElement(DropdownTriggerDiv, { ref: this.inputRef, tabIndex: tabIndex, onKeyPress: this.onEnterPress, required: !!error, style: activeValueStyle, disabled: disabled },
                            React.createElement(DropdownInputContentDiv, null, currentItem ? currentItem.value : placeholder),
                            React.createElement(ChevronDownDiv, { className: "select-str" },
                                React.createElement(ChevronDown, null)))),
                    React.createElement(PopupContainer, null,
                        React.createElement(AppDropdownContent, { list: formattedList.map((item) => (Object.assign(Object.assign({}, item), { label: item.value, value: item.id }))), className: optionsClassList, style: Object.assign({ maxHeight: heightVal + heightUnit }, dropdownStyle), ref: this.optionsRef, value: !hideSelected ? currentValue : undefined, onClick: this.onSelect, uniqueFields: uniqueFields }))))));
    }
}
Select.defaultProps = {
    maxHeight: {
        value: 350,
        unit: 'px',
    },
    withContext: true,
};
Select.contextType = FormContext;
