import { useEffect, useRef, useState } from 'react';
import { useMutation, useQueryClient } from 'react-query';

import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

import HuDialog from '@material-hu/components/design-system/Dialog';
import { DialogProps as HuDialogProps } from '@material-hu/components/design-system/Dialog/types';
import HuInputClassic from '@material-hu/components/design-system/Inputs/Classic';
import useHuSnackbar from '@material-hu/components/design-system/Snackbar';
import { deleteRole } from 'src/services/rolesAndPermissions';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { logEvent, LogEvents } from 'src/utils/logging';

import { rolesAndPermissionsKeys } from '../queries';
import { RoleListItem, RoleState } from '../types';

import { RolesAndPermissionsTableProps } from './RolesAndPermissionsTable';

type RoleDeleteDialogProps = HuDialogProps &
  Pick<RolesAndPermissionsTableProps, 'query' | 'state'> & {
    role: RoleListItem;
  };

const RoleDeleteDialog = ({
  role,
  onClose,
  query,
  state,
  ...props
}: RoleDeleteDialogProps) => {
  const [confirmationKey, setConfirmationKey] = useState('');

  const { t } = useLokaliseTranslation('rolesAndPermissions');
  const inputRef = useRef<HTMLInputElement>(null);
  const queryClient = useQueryClient();
  const { enqueueSnackbar } = useHuSnackbar();

  useEffect(() => {
    if (inputRef.current) {
      inputRef.current?.focus();
    }
  }, []);

  const deleteMutation = useMutation(() => deleteRole(role.id), {
    onSuccess: () => {
      queryClient.invalidateQueries(
        rolesAndPermissionsKeys.all(
          query,
          state === 'ALL' ? null : (state as RoleState),
        ),
      );
      enqueueSnackbar({
        title: t('delete_role_modal.success', { roleName: role.name }),
        variant: 'success',
      });
      logEvent(LogEvents.ROLE_DELETION_DONE, {
        roleId: role.id,
        state: role.state,
      });
      onClose();
    },
    onError: () => {
      enqueueSnackbar({
        title: t('delete_role_modal.error'),
        variant: 'error',
      });
    },
  });

  const handleDelete = () => deleteMutation.mutate();

  const primaryButtonDisabled =
    !confirmationKey ||
    confirmationKey.toUpperCase() !==
      t('delete_role_modal.confirmation_key').toUpperCase() ||
    deleteMutation.isLoading;

  const handleKeyDown = (
    event: React.KeyboardEvent<HTMLInputElement | HTMLTextAreaElement>,
  ) => {
    if (event.key === 'Enter' && !primaryButtonDisabled) {
      event.preventDefault();
      handleDelete();
    }
  };

  return (
    <HuDialog
      onClose={onClose}
      title={t('delete_role_modal.title')}
      primaryButtonProps={{
        children: t('delete_role_modal.primary_button'),
        onClick: handleDelete,
        disabled: primaryButtonDisabled,
        loading: deleteMutation.isLoading,
        type: 'submit',
      }}
      secondaryButtonProps={{
        children: t('general:cancel'),
        onClick: onClose,
        disabled: deleteMutation.isLoading,
      }}
      body={
        <Stack sx={{ gap: 1.5 }}>
          <Typography variant="globalS">
            {t('delete_role_modal.description', {
              roleName: role.name,
              confirmationKey: t(
                'delete_role_modal.confirmation_key',
              ).toUpperCase(),
            })}
          </Typography>
          <HuInputClassic
            inputRef={inputRef}
            label={t('delete_role_modal.input_label', {
              confirmationKey: t(
                'delete_role_modal.confirmation_key',
              ).toUpperCase(),
            })}
            value={confirmationKey}
            onChange={setConfirmationKey}
            onKeyDown={handleKeyDown}
            hasCounter={false}
            autoFocus
          />
        </Stack>
      }
      {...props}
    />
  );
};

export default RoleDeleteDialog;
