import { forwardRef, useImperativeHandle, useState } from 'react';

import {
  IconChevronDown,
  IconInfoCircle,
  IconPlus,
} from '@material-hu/icons/tabler';
import Stack from '@material-hu/mui/Stack';
import { useTheme } from '@material-hu/mui/styles';
import Typography from '@material-hu/mui/Typography';

import Button from '@material-hu/components/design-system/Buttons/Button';
import HuMenu from '@material-hu/components/design-system/Menu';
import HuMenuItem from '@material-hu/components/design-system/Menu/components/MenuItem';

import { View } from 'src/pages/dashboard/serviceManagement/types';
import { useLokaliseTranslation } from 'src/utils/i18n';

type Props = {
  onDismiss: () => void;
  onSave: () => void;
  onSaveToNewView: () => void;
  view: View | undefined;
};

const NewViewFiltersAlert = forwardRef(
  ({ onDismiss, onSave, onSaveToNewView, view }: Props, ref) => {
    const { t } = useLokaliseTranslation('service_management');
    const theme = useTheme();

    const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null);
    const open = Boolean(anchorEl);

    const toggleOptionsMenu = (event: React.MouseEvent<HTMLButtonElement>) => {
      setAnchorEl(event.currentTarget);
    };

    const handleClose = () => {
      setAnchorEl(null);
    };

    // Expose a method to close the menu from the parent
    useImperativeHandle(ref, () => ({
      closeMenu: () => {
        setAnchorEl(null);
      },
    }));

    const actions = [
      {
        label: t('save_view'),
        onClick: onSave,
      },
      {
        label: t('save_as_new_view'),
        onClick: onSaveToNewView,
      },
    ];

    return (
      <Stack
        sx={{
          backgroundColor: ({ palette }) =>
            palette.new.background.feedback.info,
          borderBottom: ({ palette }) =>
            `1px solid ${palette.new.border.states.info}`,
          py: 2,
          px: 3,
          flexDirection: 'row',
          alignItems: 'center',
          justifyContent: 'space-between',
        }}
      >
        <Stack sx={{ flexDirection: 'row', alignItems: 'center', gap: 0.5 }}>
          <IconInfoCircle color={theme.palette.new.text.feedback.info} />
          <Typography
            variant="globalS"
            fontWeight="fontWeightSemiBold"
            sx={{
              color: theme.palette.new.text.feedback.info,
            }}
          >
            {t('new_filters_applied')}
          </Typography>
        </Stack>
        <Stack sx={{ flexDirection: 'row', alignItems: 'center', gap: 1 }}>
          <Button
            variant="tertiary"
            onClick={onDismiss}
          >
            {t('dismiss')}
          </Button>
          <Stack sx={{ flexDirection: 'row', alignItems: 'center' }}>
            <Button
              variant="secondary"
              startIcon={<IconPlus />}
              sx={{
                borderTopRightRadius: view ? 0 : undefined,
                borderBottomRightRadius: view ? 0 : undefined,
                textWrap: 'nowrap',
                ...(view ? { borderRight: 0 } : {}),
              }}
              onClick={onSave}
            >
              {t('save_view')}
            </Button>
            {view && (
              <>
                <Button
                  variant="secondary"
                  onClick={toggleOptionsMenu}
                  sx={{
                    borderTopLeftRadius: 0,
                    borderBottomLeftRadius: 0,
                  }}
                >
                  <IconChevronDown
                    size={16}
                    style={{
                      transition: 'transform 0.3s ease',
                      transform: open ? 'rotate(180deg)' : 'rotate(0deg)',
                    }}
                  />
                </Button>
                <HuMenu
                  anchorEl={anchorEl}
                  open={open}
                  onClose={handleClose}
                  position="left"
                >
                  {actions.map(action => (
                    <HuMenuItem
                      key={action.label}
                      onClick={() => {
                        action.onClick();
                        // Optionally close the menu here if needed
                        handleClose();
                      }}
                    >
                      {action.label}
                    </HuMenuItem>
                  ))}
                </HuMenu>
              </>
            )}
          </Stack>
        </Stack>
      </Stack>
    );
  },
);

export default NewViewFiltersAlert;

NewViewFiltersAlert.displayName = 'NewViewFiltersAlert';
