import { getCommonTooltipProps, parseFromValuesOrFunc } from "@/core/utils/utils";
import { Box, FormControlLabel, MenuItem, Switch, Tooltip, Typography } from "@mui/material";
import { useRef, useState } from "react";
import DataTable_GrabHandleButton from "../buttons/GrabHandleButton";

const DataTable_ShowHideColumnsMenuItems = ({
    allColumns,
    column,
    hoveredColumn,
    isNestedColumns,
    setHoveredColumn,
    table,
    ...rest
}) => {
    const {
        getState,
        options: {
            enableColumnOrdering,
            enableHiding,
            localization,
            mrtTheme: { draggingBorderColor },
        },
        setColumnOrder,
    } = table;

    const { columnOrder } = getState();
    const { columnDef } = column;
    const { columnDefType } = columnDef;

    const switchChecked = column.getIsVisible();

    const handleToggleColumnHidden = (column) => {
        if (columnDefType === 'group') {
            column?.columns?.forEach?.((childColumn) => {
                childColumn.toggleVisibility(!switchChecked);
            });
        } else {
            column.toggleVisibility();
        }
    };

    const menuItemRef = useRef(null);

    const [isDragging, setIsDragging] = useState(false);

    const handleDragStart = (e) => {
        setIsDragging(true);
        try {
            e.dataTransfer.setDragImage(menuItemRef.current, 0, 0);
        } catch (e) {
            console.error(e);
        }
    };

    const handleDragEnd = (_e) => {
        setIsDragging(false);
        setHoveredColumn(null);
        if (hoveredColumn) {
            setColumnOrder(reorderColumn(column, hoveredColumn, columnOrder));
        }
    };

    const handleDragEnter = (_e) => {
        if (!isDragging && columnDef.enableColumnOrdering !== false) {
            setHoveredColumn(column);
        }
    };

    if (!columnDef.header || columnDef.visibleInShowHideMenu === false) {
        return null;
    }

    return (
        <>
            <MenuItem
                disableRipple
                onDragEnter={handleDragEnter}
                ref={menuItemRef}
                {...rest}
                sx={(theme) => ({
                    alignItems: 'center',
                    justifyContent: 'flex-start',
                    my: 0,
                    opacity: isDragging ? 0.5 : 1,
                    outline: isDragging
                        ? `2px dashed ${theme.palette.grey[500]}`
                        : hoveredColumn?.id === column.id
                            ? `2px dashed ${draggingBorderColor}`
                            : 'none',
                    outlineOffset: '-2px',
                    pl: `${(column.depth + 0.5) * 2}rem`,
                    py: '6px',
                    ...(parseFromValuesOrFunc(rest?.sx, theme)),
                })}
            >
                <Box
                    sx={{
                        display: 'flex',
                        flexWrap: 'nowrap',
                        gap: '8px',
                    }}
                >
                    {columnDefType !== 'group' &&
                        enableColumnOrdering &&
                        !isNestedColumns &&
                        (columnDef.enableColumnOrdering !== false ? (
                            <DataTable_GrabHandleButton
                                onDragEnd={handleDragEnd}
                                onDragStart={handleDragStart}
                                table={table}
                            />
                        ) : (
                            <Box sx={{ width: '28px' }} />
                        ))}
                    {enableHiding ? (
                        <FormControlLabel
                            checked={switchChecked}
                            componentsProps={{
                                typography: {
                                    sx: {
                                        mb: 0,
                                        opacity: columnDefType !== 'display' ? 1 : 0.5,
                                    },
                                },
                            }}
                            control={
                                <Tooltip
                                    {...getCommonTooltipProps()}
                                    title={localization.toggleVisibility}
                                >
                                    <Switch />
                                </Tooltip>
                            }
                            disabled={!column.getCanHide()}
                            label={columnDef.header}
                            onChange={() => handleToggleColumnHidden(column)}
                        />
                    ) : (
                        <Typography sx={{ alignSelf: 'center' }}>
                            {columnDef.header}
                        </Typography>
                    )}
                </Box>
            </MenuItem>
            {column.columns?.map((c, i) => (
                <DataTable_ShowHideColumnsMenuItems
                    allColumns={allColumns}
                    column={c}
                    hoveredColumn={hoveredColumn}
                    isNestedColumns={isNestedColumns}
                    key={`${i}-${c.id}`}
                    setHoveredColumn={setHoveredColumn}
                    table={table}
                />
            ))}
        </>
    );

}
export default DataTable_ShowHideColumnsMenuItems;