import * as React from 'react';
import {Checkbox} from '../form/Checkbox';
import {
    PropertyFilterOptionDescriptor,
    PropertyFilterMultiSelectValue,
    PropertyFilterContext
} from './types';
import {PropertyFilterTitle} from './PropertyFilterTitle';
import {propertyFieldContext} from './context';

type PropertyFilterMultiSelectProps = {
    id: string;
    title: string;
    options: Array<PropertyFilterOptionDescriptor>;
    testAutomationId: string;
};

export class PropertyFilterMultiSelect extends React.PureComponent<PropertyFilterMultiSelectProps> {
    static contextType = propertyFieldContext;

    static defaultProps = {
        testAutomationId: 'propertyFilterMultiSelect'
    };

    getValues = (context: PropertyFilterContext): PropertyFilterMultiSelectValue => {
        const {id} = this.props;
        const values = context.values[id] || [];

        if (typeof values === 'string') {
            return [];
        }

        return values;
    };

    renderOption = (
        option: PropertyFilterOptionDescriptor,
        index: number,
        values: PropertyFilterMultiSelectValue,
        onChange: Function
    ) => {
        const checked = values.includes(option.id);
        const changeHandler = () => onChange(option.id, !checked);

        return (
            <Checkbox
                className="rc-property-filter__section-item"
                data-test-automation-id={`item-${index}`}
                key={option.id}
                name={option.id}
                checked={checked}
                disabled={option.disabled}
                onChange={changeHandler}>
                {option.title}
            </Checkbox>
        );
    };

    renderRoot = (context: PropertyFilterContext) => {
        const {id, title, options, testAutomationId} = this.props;

        const values = this.getValues(context);
        const onChange = context.onChange;

        const renderOption = (option, index) =>
            this.renderOption(option, index, values, (checkboxId, value) => {
                let nextValue = new Set(values);

                if (value) {
                    nextValue.add(checkboxId);
                } else {
                    nextValue.delete(checkboxId);
                }

                onChange(id, Array.from(nextValue));
            });

        return (
            <section
                className="rc-property-filter__section"
                data-test-automation-id={testAutomationId}>
                <PropertyFilterTitle>{title}</PropertyFilterTitle>
                <div className="rc-property-filter__section-container">
                    {options.map(renderOption)}
                </div>
            </section>
        );
    };

    render() {
        return <propertyFieldContext.Consumer>{this.renderRoot}</propertyFieldContext.Consumer>;
    }
}
