import { Box, Button, Divider, Menu } from "@mui/material";
import { useMemo, useState } from "react";
import DataTable_ShowHideColumnsMenuItems from "./ShowHideColumnsMenuItems";

const DataTable_ShowHideColumnsMenu = ({ anchorEl,
    setAnchorEl,
    table,
    ...rest
}) => {
    const {
        getAllColumns,
        getAllLeafColumns,
        getCenterLeafColumns,
        getIsAllColumnsVisible,
        getIsSomeColumnsPinned,
        getIsSomeColumnsVisible,
        getLeftLeafColumns,
        getRightLeafColumns,
        getState,
        options: {
            enableColumnOrdering,
            enableColumnPinning,
            enableHiding,
            localization,
            mrtTheme: { menuBackgroundColor },
        },
    } = table;

    const { columnOrder, columnPinning, density } = getState();

    const handleToggleAllColumns = (value) => {
        getAllLeafColumns()
            .filter((col) => col.columnDef.enableHiding !== false)
            .forEach((col) => col.toggleVisibility(value));
    };

    const allColumns = useMemo(() => {
        const columns = getAllColumns();
        if (
            columnOrder.length > 0 &&
            !columns.some((col) => col.columnDef.columnDefType === 'group')
        ) {
            return [
                ...getLeftLeafColumns(),
                ...Array.from(new Set(columnOrder)).map((colId) =>
                    getCenterLeafColumns().find((col) => col?.id === colId),
                ),
                ...getRightLeafColumns(),
            ].filter(Boolean);
        }
        return columns;
    }, [
        columnOrder,
        columnPinning,
        getAllColumns(),
        getCenterLeafColumns(),
        getLeftLeafColumns(),
        getRightLeafColumns(),
    ]);

    const isNestedColumns = allColumns.some(
        (col) => col.columnDef.columnDefType === 'group',
    );

    const [hoveredColumn, setHoveredColumn] = useState(null);

    return (
        <Menu
            MenuListProps={{
                dense: density === 'compact',
                sx: {
                    backgroundColor: menuBackgroundColor,
                },
            }}
            anchorEl={anchorEl}
            disableScrollLock
            onClose={() => setAnchorEl(null)}
            open={!!anchorEl}
            {...rest}
        >
            <Box
                sx={{
                    display: 'flex',
                    justifyContent: 'space-between',
                    p: '0.5rem',
                    pt: 0,
                }}
            >
                {enableHiding && (
                    <Button
                        disabled={!getIsSomeColumnsVisible()}
                        onClick={() => handleToggleAllColumns(false)}
                    >
                        {localization.hideAll}
                    </Button>
                )}
                {enableColumnOrdering && (
                    <Button
                        onClick={() =>
                            table.setColumnOrder(
                                getDefaultColumnOrderIds(table.options, true),
                            )
                        }
                    >
                        {localization.resetOrder}
                    </Button>
                )}
                {enableColumnPinning && (
                    <Button
                        disabled={!getIsSomeColumnsPinned()}
                        onClick={() => table.resetColumnPinning(true)}
                    >
                        {localization.unpinAll}
                    </Button>
                )}
                {enableHiding && (
                    <Button
                        disabled={getIsAllColumnsVisible()}
                        onClick={() => handleToggleAllColumns(true)}
                    >
                        {localization.showAll}
                    </Button>
                )}
            </Box>
            <Divider />
            {allColumns.map((column, index) => (
                <DataTable_ShowHideColumnsMenuItems
                    allColumns={allColumns}
                    column={column}
                    hoveredColumn={hoveredColumn}
                    isNestedColumns={isNestedColumns}
                    key={`${index}-${column.id}`}
                    setHoveredColumn={setHoveredColumn}
                    table={table}
                />
            ))}
        </Menu>
    );
}
export default DataTable_ShowHideColumnsMenu