import { comparer } from 'mobx';

import { TableColumnMenuFilter } from '@servicetitan/design-system';
import { GridColumnMenuFilterProps as TableColumnMenuFilterProps } from '@progress/kendo-react-grid/dist/npm/columnMenu/GridColumnMenuFilter';
import { getDefaultOperator } from '@progress/kendo-react-grid/dist/npm/filterCommon';

import { multiselectOperators } from './multiselect-operators';

// constructor override: if state.filterGroup was filled with default, we override it with new default
export class TableColumnMenuFilterExt extends TableColumnMenuFilter {
    constructor(props: TableColumnMenuFilterProps) {
        super(props);

        const defaultOperator = getDefaultOperator(
            props.filterOperators,
            props.column.filter ?? 'text'
        );
        // I know the check is a bit hacky, but that's compensated with its low criticality: even if it fails, nothing really bad happens
        if (
            comparer.structural(this.state.filterGroup, {
                logic: 'and',
                filters: [
                    { field: props.column.field, operator: defaultOperator },
                    { field: props.column.field, operator: defaultOperator },
                ],
            })
        ) {
            const newDefaultOperator = multiselectOperators[0].operator;
            this.state = {
                ...this.state,
                filterGroup: {
                    logic: 'and',
                    filters: [
                        { field: props.column.field, operator: newDefaultOperator },
                        { field: props.column.field, operator: newDefaultOperator },
                    ],
                },
            };
        }
    }
}
