import React, { useEffect, useRef, useState } from 'react';
import { defaultTo, pipe, prop, propEq } from 'ramda';
import { checkBasicMetadataPermission, getAllowedFilterOptionsForDataTypeDefinition, getDataTypeDefinitionForFilterValue, getFilterOptionLabel, MetadataPermissions, shouldDisableTimestampLocalizationForAttribute, validateFilter } from '@reltio/mdm-sdk';
import Popover from '@mui/material/Popover';
import IconButton from '@mui/material/IconButton';
import ArrowDropDownIcon from '@mui/icons-material/ArrowDropDown';
import { FilterChip } from '../FilterChip';
import { FilterEditor } from '../../../../FilterEditor';
import { useMdmDisableTimestampLocalization } from '../../../../contexts/MdmModuleContext';
import { columnFilterToMdmFilter } from '../../../../helpers/basicTable';
import { mdmFilterToColumnFilter } from './helpers';
import { useStyles } from '../../styles';
export var ColumnFilter = function (_a) {
    var _b;
    var columnId = _a.columnId, dataTypeDefinition = _a.dataTypeDefinition, filter = _a.filter, filterOptionsData = _a.filterOptionsData, onFilter = _a.onFilter;
    var styles = useStyles();
    var disableTimestampLocalizationFlag = useMdmDisableTimestampLocalization();
    var disableTimestampLocalizationForFilterValue = shouldDisableTimestampLocalizationForAttribute(dataTypeDefinition, { disableTimestampLocalization: disableTimestampLocalizationFlag });
    var _c = useState(null), anchorEl = _c[0], setAnchorEl = _c[1];
    var openFilterPopup = function (event) { return setAnchorEl(event.currentTarget); };
    var closeFilterPopup = function () { return setAnchorEl(null); };
    var _d = useState(filter), columnFilter = _d[0], setColumnFilter = _d[1];
    useEffect(function () {
        setColumnFilter(filter);
    }, [filter]);
    var containerRef = useRef(null);
    var mdmFilter = columnFilterToMdmFilter({ id: columnId, dataTypeDefinition: dataTypeDefinition }, columnFilter, {
        disableTimestampLocalization: disableTimestampLocalizationFlag
    });
    var applyFilterChange = function (newFilter) {
        if (newFilter !== filter) {
            onFilter({ columnId: columnId, filter: newFilter });
        }
    };
    var clearFilter = function () { return applyFilterChange(); };
    var applyChangesAndClose = function () {
        var isValidFilter = validateFilter(mdmFilter);
        if (isValidFilter) {
            applyFilterChange(columnFilter);
        }
        else {
            clearFilter();
        }
        closeFilterPopup();
    };
    var handleValueEditorKeyPress = function (event) {
        if (event.key !== 'Enter')
            return;
        event.stopPropagation();
        event.preventDefault();
        applyChangesAndClose();
    };
    var getFilterOptionData = function (filterOption) {
        return filterOptionsData && filterOptionsData.find(propEq('value', filterOption));
    };
    var getFilterLabel = function (filterOption) {
        return pipe(getFilterOptionData, prop('label'), defaultTo(getFilterOptionLabel(filterOption)))(filterOption);
    };
    var getFilterDataTypeDefinition = function (filterOption) {
        return pipe(getFilterOptionData, prop('dataTypeDefinition'), defaultTo(getDataTypeDefinitionForFilterValue(dataTypeDefinition, filterOption, {
            disableTimestampLocalization: disableTimestampLocalizationForFilterValue
        })))(filterOption);
    };
    var filterOptionValues = (_b = filterOptionsData === null || filterOptionsData === void 0 ? void 0 : filterOptionsData.map(function (filterOption) { return filterOption.value; })) !== null && _b !== void 0 ? _b : getAllowedFilterOptionsForDataTypeDefinition(dataTypeDefinition);
    var filterOptions = filterOptionValues.map(function (value) { return ({ value: value, label: getFilterLabel(value) }); });
    var hasReadPermission = checkBasicMetadataPermission(MetadataPermissions.READ, dataTypeDefinition);
    return (React.createElement("div", { ref: containerRef, className: styles.columnFilter, "data-reltio-id": "column-filter" },
        filter && (React.createElement(FilterChip, { filterValue: filter.value, filterOption: filterOptions.find(propEq('value', filter.filter)), onDelete: clearFilter, dataTypeDefinition: getFilterDataTypeDefinition(filter.filter) })),
        hasReadPermission && (React.createElement(IconButton, { className: styles.dropDownButton, onClick: openFilterPopup, disableFocusRipple: true, size: "large" },
            React.createElement(ArrowDropDownIcon, null))),
        React.createElement(Popover, { PaperProps: {
                style: {
                    width: "".concat(containerRef.current ? containerRef.current.getBoundingClientRect().width : 0, "px")
                }
            }, open: !!anchorEl, anchorEl: anchorEl, anchorOrigin: {
                vertical: 'bottom',
                horizontal: 'right'
            }, transformOrigin: {
                vertical: 'top',
                horizontal: 'right'
            }, classes: { paper: styles.filterMenu }, onClose: applyChangesAndClose },
            React.createElement(FilterEditor, { classes: { option: styles['filter-editor__option'] }, value: mdmFilter, onChange: pipe(mdmFilterToColumnFilter, setColumnFilter), filterOptions: filterOptions, dataTypeDefinition: getFilterDataTypeDefinition(mdmFilter.filter), ValueEditorProps: {
                    TextFieldProps: {
                        onKeyPress: handleValueEditorKeyPress
                    },
                    fullWidth: true
                } }))));
};
