import { useCallback, useMemo, useState } from 'react';
import { useNavigate } from 'react-router-dom';

import {
  IconArrowsMaximize,
  IconBed,
  IconCalendarDue,
  IconCalendarPlus,
  IconCalendarX,
  IconCirclePlus,
  IconClipboard,
  IconCopy,
  IconDeselect,
  IconDots,
  IconSelectAll,
} from '@material-hu/icons/tabler';
import IconButton from '@material-hu/mui/IconButton';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

import HuMenu from '@material-hu/components/design-system/Menu';
import Tooltip from '@material-hu/components/design-system/Tooltip';

import { logEvent } from 'src/config/amplitude';
import { queryClient } from 'src/config/react-query';
import { useAuth } from 'src/contexts/JWTContext';
import { useLayoutContext } from 'src/contexts/LayoutContext';
import useFormatDate from 'src/hooks/useFormatDate';
import { profileKeys } from 'src/pages/dashboard/profile/queries';
import { type AssignShiftParams } from 'src/services/shifts';
import { getPublicUsers } from 'src/services/users';
import {
  EventName,
  ShiftManagementMenuOption,
  ShiftManagementMenuSource,
} from 'src/types/amplitude';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { formatShortcut } from 'src/utils/keyboardShortcuts';
import { getClientOs } from 'src/utils/platform';

import { useShiftsSelectionActions } from '../contexts/ShiftsSelectionContext';
import { CUSTOM_SHIFT_INITIAL_VALUES } from '../form';
import { prefetchShiftsRepositoryFirstPage } from '../queries';
import { shiftsRoutes } from '../routes';
import {
  checkIfUserIsShiftManager,
  getAssignmentParams,
  type ShiftFilters,
} from '../utils';

import MenuItemOption from './MenuItemOption';
import Button from '@material-hu/components/design-system/Buttons/Button';

/* COACHMARK DISABLED - kept for future reference
import { useShiftsCoachmark } from './ShiftsCoachmark';
import { COACHMARK_ELEMENT_IDS } from './ShiftsCoachmark/constants';
*/

type Props = {
  onOpenCustomShiftDrawer: (props: Partial<unknown>) => void;
  onRemoveAllShifts: () => void;
  onAssignDayOff?: (params: AssignShiftParams) => void;
  debouncedValues?: ShiftFilters;
  showAssigningModal?: () => void;
  onCopy: () => void;
  onPaste: () => void;
  onOpenDuplicateShiftsDrawer: () => void;
  onToggleSelect: () => void;
};

const ActionButtons = ({
  onOpenCustomShiftDrawer,
  onRemoveAllShifts,
  onAssignDayOff,
  debouncedValues = {},
  showAssigningModal,
  onCopy,
  onPaste,
  onOpenDuplicateShiftsDrawer,
  onToggleSelect,
}: Props) => {
  const { t } = useLokaliseTranslation(['shifts', 'general']);
  const navigate = useNavigate();
  const { formatDate } = useFormatDate();
  const [actionMenuAnchorEl, setActionMenuAnchorEl] =
    useState<HTMLButtonElement | null>(null);
  const [dotsMenuAnchorEl, setDotsMenuAnchorEl] =
    useState<HTMLButtonElement | null>(null);
  const { user, permissions } = useAuth();
  const { taskFocus, setTaskFocus } = useLayoutContext();

  // COACHMARK DISABLED: dotsButtonRef was only read by the coachmark step 3 logic below.
  // const dotsButtonRef = useRef<HTMLButtonElement>(null);

  /* COACHMARK DISABLED - kept for future reference
  // Coachmark integration
  const { hasCompletedCoachmark, currentStep, registerOpenStep3Menu } =
    useShiftsCoachmark();

  // Register callback to open dots menu for step 3
  useEffect(() => {
    registerOpenStep3Menu(() => {
      return new Promise(resolve => {
        if (dotsButtonRef.current) {
          setDotsMenuAnchorEl(dotsButtonRef.current);
          // Wait for menu to fully render, then return the copyOption element
          // Use requestAnimationFrame to wait for DOM update, then setTimeout for animation
          requestAnimationFrame(() => {
            setTimeout(() => {
              const element = document.getElementById(
                COACHMARK_ELEMENT_IDS.copyOption,
              );
              resolve(element);
            }, 150);
          });
        } else {
          resolve(null);
        }
      });
    });
  }, [registerOpenStep3Menu]);
  */

  const userIsShiftManager = checkIfUserIsShiftManager(permissions);

  const closeOverlayCleanup = useCallback(() => {
    setActionMenuAnchorEl(null);
    setDotsMenuAnchorEl(null);
  }, []);
  const {
    selectedCells,
    selectedDates,
    selectedShifts,
    excludeCells,
    copiedCells,
    allRowsSelected,
  } = useShiftsSelectionActions({ closeOverlayCleanup });

  const ACTION_OPTIONS = useMemo(
    () => [
      // TODO: Future PR: Add collaborator
      {
        icon: IconCalendarPlus,
        text: t('assign_shift'),
        onClick: () => {
          prefetchShiftsRepositoryFirstPage();
          onOpenCustomShiftDrawer({
            openOn: 'shift',
          });
        },
      },
      {
        icon: IconBed,
        text: t('assign_rest'),
        onClick: () => {
          // If there are selections, assign directly the day off
          if (selectedDates.size > 0 || selectedCells.length > 0) {
            if (onAssignDayOff && showAssigningModal) {
              showAssigningModal();
              onAssignDayOff(
                getAssignmentParams({
                  data: CUSTOM_SHIFT_INITIAL_VALUES,
                  formatDate,
                  selectedDates,
                  selectedCells,
                  excludeCells,
                  filters: debouncedValues,
                  saveAsTemplate: false,
                }),
              );
            }
          } else {
            // If there are no selections, open the drawer
            onOpenCustomShiftDrawer({
              openOn: 'day_off',
            });
          }
        },
      },
    ],
    [
      onOpenCustomShiftDrawer,
      onAssignDayOff,
      selectedDates,
      selectedCells,
      excludeCells,
      debouncedValues,
      formatDate,
      showAssigningModal,
      t,
    ],
  );

  const isRemoveAllShiftsDisabled =
    selectedCells.length === 0 &&
    selectedDates.size === 0 &&
    selectedShifts.size === 0;

  const isEverythingSelected = allRowsSelected && excludeCells.length === 0;

  return (
    <>
      <Stack sx={{ alignItems: 'stretch', flexDirection: 'row', gap: 1 }}>
        <IconButton
          aria-label={t('cells_actions_menu')}
          variant="secondary"
          onClick={event => {
            setActionMenuAnchorEl(event.currentTarget);
            queryClient.prefetchQuery(
              profileKeys.userList(''),
              () => getPublicUsers({ page: 1, limit: 30, search: undefined }),
              {
                staleTime: 1000 * 60 * 2,
              },
            );
          }}
        >
          <IconCirclePlus />
        </IconButton>
        <IconButton
          // COACHMARK DISABLED: ref={dotsButtonRef}
          aria-label={t('shifts_actions_menu')}
          variant="secondary"
          onClick={event => {
            setDotsMenuAnchorEl(event.currentTarget);
          }}
        >
          <IconDots />
        </IconButton>
        {userIsShiftManager && (
          <Button
            variant="secondary"
            startIcon={<IconCalendarDue />}
            sx={{ height: '100%' }}
            onClick={() => navigate(shiftsRoutes.repository())}
          >
            {t('shifts_repository')}
          </Button>
        )}
        {!taskFocus && (
          <Tooltip
            title={t('toggle_on_full_screen')}
            slotProps={{
              popper: {
                placement: 'top-start',
              },
            }}
          >
            <IconButton
              aria-label={t('toggle_on_full_screen')}
              variant="tertiary"
              onClick={() => {
                logEvent(EventName.SHIFT_MANAGEMENT_FULLSCREEN, {});
                setTaskFocus(true);
              }}
            >
              <IconArrowsMaximize />
            </IconButton>
          </Tooltip>
        )}
      </Stack>
      <HuMenu
        anchorEl={actionMenuAnchorEl}
        open={!!actionMenuAnchorEl}
        aria-hidden={!!actionMenuAnchorEl}
        onClose={() => {
          setActionMenuAnchorEl(null);
        }}
        position="left"
        sx={{ minWidth: 312, zIndex: 2 }}
      >
        {ACTION_OPTIONS.map(({ icon, onClick, text }) => (
          <MenuItemOption
            key={text}
            icon={icon}
            onClick={() => {
              setActionMenuAnchorEl(null);
              onClick();
            }}
            titleText={text}
          />
        ))}
      </HuMenu>
      <HuMenu
        // COACHMARK DISABLED: anchorEl/open used to also reflect coachmark step 3
        anchorEl={dotsMenuAnchorEl}
        open={!!dotsMenuAnchorEl}
        onClose={() => {
          setDotsMenuAnchorEl(null);
        }}
        position="left"
        sx={{
          zIndex: 2,
          '& .MuiPaper-root': {
            maxHeight: 'unset',
            minWidth: 352,
          },
          '& .MuiList-root': {
            maxHeight: 'unset',
            minWidth: 352,
            pt: 1,
          },
        }}
      >
        <Typography
          variant="globalXS"
          sx={{ px: 2, pb: 1 }}
        >
          {t('general:action_label')}
        </Typography>
        <MenuItemOption
          icon={IconCalendarX}
          onClick={() => {
            onRemoveAllShifts();
            logEvent(EventName.SHIFT_MANAGEMENT_MENU_USED, {
              option_used: ShiftManagementMenuOption.REMOVE_SHIFT,
              menu: ShiftManagementMenuSource.GLOBAL,
            });
          }}
          titleText={t('remove_all_shifts')}
          disabled={isRemoveAllShiftsDisabled}
          hintText={getClientOs() === 'MacOS' ? 'Delete' : 'Supr'}
        />
        <MenuItemOption
          // COACHMARK DISABLED: id={COACHMARK_ELEMENT_IDS.copyOption}, hovered={!hasCompletedCoachmark}
          icon={IconCopy}
          onClick={() => {
            setDotsMenuAnchorEl(null);
            onCopy();
            logEvent(EventName.SHIFT_MANAGEMENT_MENU_USED, {
              option_used: ShiftManagementMenuOption.COPY,
              menu: ShiftManagementMenuSource.GLOBAL,
            });
          }}
          titleText={t('general:copy')}
          disabled={!selectedCells.length && !selectedShifts.size}
          hintText={formatShortcut('C')}
        />
        <MenuItemOption
          icon={IconClipboard}
          onClick={() => {
            setDotsMenuAnchorEl(null);
            onPaste();
            logEvent(EventName.SHIFT_MANAGEMENT_MENU_USED, {
              option_used: ShiftManagementMenuOption.PASTE,
              menu: ShiftManagementMenuSource.GLOBAL,
            });
          }}
          titleText={t('general:paste')}
          disabled={!copiedCells.length}
          hintText={formatShortcut('V')}
        />
        <MenuItemOption
          icon={isEverythingSelected ? IconDeselect : IconSelectAll}
          onClick={() => {
            setDotsMenuAnchorEl(null);
            onToggleSelect();
            logEvent(EventName.SHIFT_MANAGEMENT_MENU_USED, {
              option_used: isEverythingSelected
                ? ShiftManagementMenuOption.UNSELECT_ALL
                : ShiftManagementMenuOption.SELECT_ALL,
              menu: ShiftManagementMenuSource.GLOBAL,
            });
          }}
          titleText={
            isEverythingSelected
              ? t('actions.selection.unselect_all')
              : t('actions.selection.select_all')
          }
          hintText={isEverythingSelected ? 'Esc' : formatShortcut('A')}
        />
        <Stack sx={{ gap: 1, pt: 1 }}>
          <Typography
            variant="globalXS"
            sx={{ px: 2 }}
          >
            {t('advanced')}
          </Typography>
          <MenuItemOption
            onClick={() => {
              onOpenDuplicateShiftsDrawer();
              setDotsMenuAnchorEl(null);
              logEvent(EventName.SHIFT_MANAGEMENT_MENU_USED, {
                option_used: ShiftManagementMenuOption.DUPLICATE,
                menu: ShiftManagementMenuSource.GLOBAL,
              });
            }}
            titleText={t('duplicate_shifts_period.duplicate_planification')}
            descriptionText={t(
              'duplicate_shifts_period.duplicate_planification_description',
            )}
          />
        </Stack>
      </HuMenu>
    </>
  );
};

export default ActionButtons;
