import React from "react";
import { AppIconDefaultIcon, BlockedIcon, BulletedTreeListIcon, CombineIcon, ExportIcon, FavoriteStarIcon, FilterIcon, LightbulbIcon, MoreVerticalIcon, SaveIcon, SearchIcon, TripleColumnIcon, UploadIcon } from '@fluentui/react-icons';
import { InputAdornment, MenuItem, Popover, Typography, makeStyles } from '@material-ui/core';
import PropTypes from 'prop-types';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { FluentIcon } from '../../../../utilities/iconLibrary/FluentIcon';
import { AmbientChipButton } from '../../../inputs/buttons/AmbientChipButton';
import { AmbientTokenButton } from '../../../inputs/buttons/AmbientTokenButton';
import PrimaryActionButton from '../../../inputs/buttons/PrimaryActionButton';
import { AmbientTextField } from '../../../inputs/textField/AmbientTextField';
const useStyles = makeStyles((theme) => ({
    root: {
        display: 'flex',
        flexDirection: 'row',
        padding: theme.spacing(0.5)
        // background: (props) =>
        //   props.background
        //     ? props.background
        //     : lighten(theme.palette.secondary.light, 0.9)
    },
    label: {
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'flex-end'
    },
    title: {
        flex: 1,
        display: 'flex',
        alignItems: 'center',
        marginLeft: (props) => (props.title ? theme.spacing(2) : 0)
    },
    // @todo: switch to Fluent tabs and remove this style
    tabRoot: {
        minWidth: 0,
        textTransform: 'none'
    },
    controls: {
        display: 'flex',
        alignItems: 'center',
        gridGap: theme.spacing(2),
        gap: theme.spacing(2),
        marginRight: theme.spacing(2)
    },
    icon: {
        background: theme.palette.common.white,
        padding: theme.spacing(1),
        color: theme.palette.primary.main
    }
}));
/** @deprecated Use the new grid. */
export const GridPrimaryBar = (props) => {
    const classes = useStyles(props);
    const { children, onChange, fitClick, expandClick, clearClick, exportClick, filterClick, columnsClick, groupClick, title, hiddenActionButtons, hiddenLabels, hideSearchBar = false, secondaryActionButtons, saveViewClick, viewsClick, insightsClick, onPrimaryActionClick, primaryActionDisabled, primaryActionLabel, primaryActionIcon, onSearchKeyDown } = props;
    const [actionButtonMedianPx, setActionButtonMedianPx] = useState(0);
    const [actionButtons, setActionButtons] = useState([]);
    const [menuActionButtons, setMenuActionButtons] = useState([]);
    const [anchorEl, setAnchorEl] = useState(null);
    const [windowWidthBreakpoint, setWindowWidthBreakpoint] = useState(1400);
    const chipButtonSizePx = 100;
    const tokenButtonSizePx = 40;
    const open = Boolean(anchorEl);
    const id = open ? 'simple-popover' : undefined;
    const defaultActionButtons = useMemo(() => [
        {
            icon: SaveIcon,
            tooltip: 'Save Grid Configuration',
            label: 'Save View',
            visible: !hiddenActionButtons.includes('saveView'),
            hideLabel: hiddenLabels.includes('saveView'),
            onClick: saveViewClick,
            background: 'transparent'
        },
        {
            icon: FavoriteStarIcon,
            tooltip: 'Browse Views',
            label: 'Views',
            visible: !hiddenActionButtons.includes('views'),
            onClick: viewsClick,
            hideLabel: hiddenLabels.includes('views'),
            iconClassName: classes.icon
        },
        {
            icon: LightbulbIcon,
            tooltip: 'Insights',
            label: 'Insights',
            visible: !hiddenActionButtons.includes('insights'),
            hideLabel: hiddenLabels.includes('insights'),
            onClick: insightsClick,
            iconClassName: classes.icon
        },
        {
            icon: UploadIcon,
            tooltip: 'Import/Export',
            label: 'Import/Export',
            visible: !!exportClick && !hiddenActionButtons.includes('importExport'),
            hideLabel: hiddenLabels.includes('importExport'),
            onClick: exportClick,
            iconClassName: classes.icon
        },
        {
            icon: BulletedTreeListIcon,
            tooltip: 'Group',
            label: 'Group',
            visible: !!groupClick && !hiddenActionButtons.includes('group'),
            hideLabel: hiddenLabels.includes('group'),
            onClick: groupClick,
            iconClassName: classes.icon
        },
        {
            icon: FilterIcon,
            tooltip: 'Filter',
            label: 'Filter',
            visible: !!filterClick && !hiddenActionButtons.includes('filter'),
            hideLabel: hiddenLabels.includes('filter'),
            onClick: filterClick,
            iconClassName: classes.icon
        },
        {
            icon: TripleColumnIcon,
            tooltip: 'Columns',
            label: 'Columns',
            visible: !!columnsClick && !hiddenActionButtons.includes('columns'),
            hideLabel: hiddenLabels.includes('columns'),
            onClick: columnsClick,
            iconClassName: classes.icon
        },
        {
            icon: CombineIcon,
            tooltip: 'Fit Grid',
            label: 'Fit Grid',
            visible: !!fitClick && !hiddenActionButtons.includes('fitGrid'),
            hideLabel: hiddenLabels.includes('fitGrid'),
            onClick: fitClick,
            iconClassName: classes.icon
        },
        {
            icon: ExportIcon,
            tooltip: 'Expand Grid',
            label: 'Expand Grid',
            visible: !!expandClick && !hiddenActionButtons.includes('expandGrid'),
            hideLabel: hiddenLabels.includes('expandGrid'),
            onClick: expandClick,
            iconClassName: classes.icon
        },
        {
            icon: BlockedIcon,
            tooltip: 'Clear Filters',
            label: 'Clear Filters',
            visible: !!clearClick && !hiddenActionButtons.includes('clearFilters'),
            hideLabel: hiddenLabels.includes('clearFilters'),
            onClick: clearClick,
            iconClassName: classes.icon
        }
    ], [
        classes.icon,
        clearClick,
        columnsClick,
        expandClick,
        exportClick,
        filterClick,
        fitClick,
        groupClick,
        hiddenActionButtons,
        hiddenLabels,
        insightsClick,
        saveViewClick,
        viewsClick
    ]);
    const handlePopoverClick = (event) => {
        setAnchorEl(event.currentTarget);
    };
    const handlePopoverClose = () => {
        setAnchorEl(null);
    };
    const formatActionButtons = useCallback((buttons) => {
        // This allows users to not have to set the visible and showLabel properties when passing secondaryActionButtons
        return buttons.map((button) => {
            var _a;
            if (button.visible === undefined) {
                button.visible = true;
            }
            if (button.hideLabel === undefined) {
                button.hideLabel = false;
            }
            if (button.label === undefined) {
                button.label = (_a = button.tooltip) !== null && _a !== void 0 ? _a : 'Button';
                button.hideLabel = true;
            }
            if (button.iconClassName === undefined &&
                button.background === undefined) {
                button.iconClassName = classes.icon;
            }
            return button;
        });
    }, [classes === null || classes === void 0 ? void 0 : classes.icon]);
    // calculate the action buttons to display based on the window width
    useEffect(() => {
        const allActionButtons = formatActionButtons([
            ...defaultActionButtons,
            ...secondaryActionButtons
        ]);
        const menuButtons = [];
        const numActionButtons = allActionButtons.length - hiddenActionButtons.length;
        const buttonTotalWidth = numActionButtons * chipButtonSizePx -
            (chipButtonSizePx - tokenButtonSizePx) * hiddenLabels.length;
        const calculatedMedian = Math.floor(buttonTotalWidth / numActionButtons);
        const breakPointOffset = calculatedMedian > 70 ? 950 : 900;
        let breakPoint = breakPointOffset + buttonTotalWidth;
        const currentWindowWidth = window.innerWidth;
        while (currentWindowWidth < breakPoint && allActionButtons.length > 0) {
            const movedAction = allActionButtons.pop();
            menuButtons.push(movedAction);
            breakPoint -= calculatedMedian;
        }
        setActionButtonMedianPx(calculatedMedian);
        setActionButtons(allActionButtons);
        setMenuActionButtons(menuButtons);
        setWindowWidthBreakpoint(breakPoint);
    }, [
        formatActionButtons,
        defaultActionButtons,
        secondaryActionButtons,
        hiddenActionButtons === null || hiddenActionButtons === void 0 ? void 0 : hiddenActionButtons.length,
        hiddenLabels === null || hiddenLabels === void 0 ? void 0 : hiddenLabels.length
    ]);
    useEffect(() => {
        const handleResize = () => {
            let breakPoint = windowWidthBreakpoint;
            let visibleButtons = [...actionButtons];
            let menuButtons = [...menuActionButtons];
            while (window.innerWidth < breakPoint && visibleButtons.length > 0) {
                const movedAction = visibleButtons.pop();
                menuButtons.push(movedAction);
                breakPoint -= actionButtonMedianPx;
            }
            while (window.innerWidth > breakPoint + actionButtonMedianPx &&
                menuButtons.length > 0) {
                const movedAction = menuButtons.pop(0);
                visibleButtons.push(movedAction);
                breakPoint += actionButtonMedianPx;
            }
            setActionButtons(visibleButtons);
            setMenuActionButtons(menuButtons);
            setWindowWidthBreakpoint(breakPoint);
        };
        window.addEventListener('resize', handleResize);
        return () => {
            window.removeEventListener('resize', handleResize);
        };
    }, [
        windowWidthBreakpoint,
        actionButtons,
        menuActionButtons,
        actionButtonMedianPx
    ]);
    const handleCustomKeyDown = (event) => {
        if (onSearchKeyDown) {
            if (event.key === 'Enter') {
                onSearchKeyDown();
            }
        }
    };
    return (React.createElement("div", { className: classes.root }, React.createElement("div", { className: classes.title }, title && (React.createElement(Typography, { variant: "h6", style: {
            overflow: 'hidden',
            whiteSpace: 'nowrap',
            textOverflow: 'ellipsis'
        } }, ' ', title, ' ')), !hideSearchBar && (React.createElement("div", { style: {
            flex: 1,
            marginLeft: 16,
            marginRight: 16,
            marginTop: -16,
            maxWidth: 300
        } }, React.createElement(AmbientTextField, { title: title, onChange: onChange, onKeyDown: handleCustomKeyDown, InputProps: {
            type: 'search',
            startAdornment: (React.createElement(InputAdornment, { position: "start" }, React.createElement(SearchIcon, null)))
        } })))), React.createElement("div", { className: classes.controls }, actionButtons.map((button) => {
        var _a, _b;
        return button.visible &&
            (button.hideLabel ? (React.createElement(AmbientTokenButton, { id: 'udpRecord-GridPrimaryBar-Token-' +
                    button.label.replace(/ /g, '-'), udprecordid: 'udpRecord-GridPrimaryBar-Token-' +
                    button.label.replace(/ /g, '-'), icon: (_a = button.icon) !== null && _a !== void 0 ? _a : AppIconDefaultIcon, tooltip: button.tooltip, onClick: button.onClick, ariaLabel: button.label, iconClassName: button.iconClassName })) : (React.createElement(AmbientChipButton, { id: 'udpRecord-GridPrimaryBar-Chip-' +
                    button.label.replace(/ /g, '-'), udprecordid: 'udpRecord-GridPrimaryBar-Chip-' +
                    button.label.replace(/ /g, '-'), icon: (_b = button.icon) !== null && _b !== void 0 ? _b : AppIconDefaultIcon, tooltip: button.tooltip, label: button.label, onClick: button.onClick, background: button.background })));
    }), !!menuActionButtons.length && (React.createElement("div", null, React.createElement(AmbientTokenButton, { id: id, icon: MoreVerticalIcon, tooltip: "More Actions", ariaLabel: "More Actions", onClick: handlePopoverClick, iconClassName: classes.icon }), React.createElement(Popover, { id: id, open: open, anchorEl: anchorEl, onClose: handlePopoverClose, anchorOrigin: {
            vertical: 'bottom',
            horizontal: 'right'
        }, transformOrigin: {
            vertical: 'top',
            horizontal: 'right'
        } }, menuActionButtons
        .slice(0)
        .reverse()
        .map((button) => {
        var _a;
        if (!button.visible)
            return null;
        return (React.createElement(MenuItem, { id: 'udpRecord-GridPrimaryBar-MenuItem-' +
                button.label.replace(/ /g, '-'), udprecordid: 'udpRecord-GridPrimaryBar-MenuItem-' +
                button.label.replace(/ /g, '-'), onClick: button.onClick, style: {
                display: 'flex',
                justifyContent: 'space-between'
            } }, React.createElement(Typography, null, button.label), React.createElement(FluentIcon, { component: (_a = button.icon) !== null && _a !== void 0 ? _a : AppIconDefaultIcon, style: { marginLeft: 7 } })));
    }))))), onPrimaryActionClick && (React.createElement(PrimaryActionButton, { onClick: onPrimaryActionClick, id: "udpRecord-GridPrimaryBar-Add", udprecordid: "udpRecord-GridPrimaryBar-Add", disabled: primaryActionDisabled }, React.createElement(Typography, { style: { marginLeft: 4 } }, primaryActionLabel !== null && primaryActionLabel !== void 0 ? primaryActionLabel : 'Button'), React.createElement(FluentIcon, { style: { marginLeft: 7 }, component: primaryActionIcon !== null && primaryActionIcon !== void 0 ? primaryActionIcon : AppIconDefaultIcon })))));
};
GridPrimaryBar.propTypes = {
    /**
     * Title of the action bar
     */
    title: PropTypes.string,
    /**
     * Child content to add within action bar
     */
    children: PropTypes.node,
    /**
     * The event that occurs when the grid changes due to a search
     */
    onChange: PropTypes.func,
    /**
     * Passes click event to function for fit to grid
     */
    fitClick: PropTypes.func,
    /**
     * Passes click event to function for expanding grid
     */
    expandClick: PropTypes.func,
    /**
     * Passes click event to function for clearing filters
     */
    clearClick: PropTypes.func,
    /**
     * Passes click event to function for exporting grid
     */
    exportClick: PropTypes.func,
    /**
     * Passes function that executes on the insights button click
     */
    insightsClick: PropTypes.func,
    /**
     * Passes click event to function for filtering grid
     */
    filterClick: PropTypes.func,
    /**
     * Passes click event to function for disabling columns in grid
     */
    columnsClick: PropTypes.func,
    /**
     * Passes click event to function for grouping grid
     */
    groupClick: PropTypes.func,
    /**
     * Specifies whether to hide the search bar
     */
    hideSearchBar: PropTypes.bool,
    /**
     * An optional array of secondary action buttons to display.
     * Required minimum format:
     *  {
          tooltip: 'Description',
          label: 'Label',
          onClick: () => console.log('Button clicked'),
        },
     */
    secondaryActionButtons: PropTypes.arrayOf(PropTypes.object),
    /*
     * Specifies which action buttons to hide
     */
    hiddenActionButtons: PropTypes.arrayOf(PropTypes.oneOf([
        'saveView',
        'views',
        'insights',
        'importExport',
        'group',
        'filter',
        'columns',
        'fitGrid',
        'expandGrid',
        'clearFilters'
    ])),
    /*
     * Specifies which action button labels to hide
     */
    hiddenLabels: PropTypes.arrayOf(PropTypes.oneOf([
        'saveView',
        'views',
        'insights',
        'importExport',
        'group',
        'filter',
        'columns',
        'fitGrid',
        'expandGrid',
        'clearFilters'
    ])),
    /**
     * Passes function that executes on the primary action button click
     */
    onPrimaryActionClick: PropTypes.func,
    /**
     * Specifies the label for the primary action button
     */
    primaryActionLabel: PropTypes.string,
    /**
     * Specifies the icon for the primary action button
     */
    primaryActionIcon: PropTypes.elementType
};
//# sourceMappingURL=GridPrimaryBar.js.map