import { FC, SyntheticEvent } from 'react';

import { NumericTextBox, NumericTextBoxChangeEvent } from '@progress/kendo-react-inputs';
import { DropDownList, DropDownListChangeEvent } from '@progress/kendo-react-dropdowns';

import { GridColumnMenuFilterCellProps as TableColumnMenuFilterCellProps } from '@progress/kendo-react-grid/dist/npm/columnMenu/GridColumnMenuFilterCell';
import {
    IsUnaryFilter,
    cellOperatorChange,
} from '@progress/kendo-react-grid/dist/npm/filterCommon';

import { numericExtendedOperators, isNumericExtendedOperator } from './numeric-extended-operators';

import { renderCustomColumnMenuFilter } from '../column-menu-filters';
//

// like standard filter cell (rendered for numeric type), but with support of some special numeric operators
const NumericExtFilterCell: FC<TableColumnMenuFilterCellProps> = ({
    operators,
    operator = '',
    value,
    onChange,
}) => {
    const operatorsExt = operators.concat(numericExtendedOperators);
    const operatorValue = operatorsExt.find(item => item.operator === operator);

    const handleInputChange = (e: NumericTextBoxChangeEvent) =>
        onChange({
            operator,
            value: e.value,
            syntheticEvent: e.syntheticEvent,
        });

    const handleOperatorChange = (event: DropDownListChangeEvent) => {
        // set value to 0 when switching to unary operator to allow select
        const newValue = isNumericExtendedOperator(event.target.value.operator) ? 0 : value;
        cellOperatorChange(event, newValue, onChange);
    };

    const isUnary =
        (typeof operator === 'string' && IsUnaryFilter(operator)) ||
        isNumericExtendedOperator(operator);

    return (
        <div>
            <DropDownList
                className="m-b-1"
                value={operatorValue}
                onChange={handleOperatorChange}
                data={operatorsExt}
                textField="text"
            />
            <NumericTextBox
                value={isUnary ? null : value}
                onChange={handleInputChange}
                disabled={isUnary}
                className="m-b-1"
            />
        </div>
    );
};
const PercentageExtFilterCell: FC<TableColumnMenuFilterCellProps> = ({
    onChange,
    value,
    ...restProps
}) => {
    const handleInputChange = (event: {
        value: any;
        operator: string | Function;
        syntheticEvent: SyntheticEvent<any>;
    }) => {
        onChange({ ...event, value: event.value ? event.value / 100 : event.value });
    };
    return (
        <NumericExtFilterCell
            onChange={handleInputChange}
            value={value ? value * 100 : value}
            {...restProps}
        />
    );
};

export const NumericFilterExtended = renderCustomColumnMenuFilter(NumericExtFilterCell, true);

export const PercentageFilterExtended = renderCustomColumnMenuFilter(PercentageExtFilterCell, true);
