import { lazy, Suspense } from 'react';
import { useNavigate } from 'react-router-dom';

import { useModal } from '@material-hu/hooks/useModal';

import MenuList, {
  type MenuListProps,
} from '@material-hu/components/composed-components/MenuList';
import TableCell from '@material-hu/components/design-system/Table/components/TableCell';

import { queryClient } from 'src/config/react-query';
import { SessionStatus } from 'src/pages/dashboard/Learning/Sessions/constants';
import { useEditPartialSession } from 'src/pages/dashboard/Learning/Sessions/hooks/useEditPartialSession';
import { sessionsKeys } from 'src/pages/dashboard/Learning/Sessions/queries';
import { sessionsRoutes } from 'src/pages/dashboard/Learning/Sessions/routes';
import { type SessionStatusType } from 'src/pages/dashboard/Learning/Sessions/types';
import { insertIf } from 'src/utils/arrayUtils';
import { useLokaliseTranslation } from 'src/utils/i18n';

const DeleteSessionDialog = lazy(() => import('../DeleteSessionDialog'));

type TableRowActionsProps = {
  sessionId: number;
  sessionStatus: SessionStatusType;
};

export const TableRowActions = ({
  sessionId,
  sessionStatus,
}: TableRowActionsProps) => {
  const navigate = useNavigate();
  const { t } = useLokaliseTranslation('learning');

  const deleteSessionDialog = useModal(
    () => (
      <Suspense>
        <DeleteSessionDialog
          sessionId={sessionId}
          onClose={deleteSessionDialog.closeModal}
        />
      </Suspense>
    ),
    { onClick: e => e.stopPropagation() },
  );

  const { mutate: editPartialSession, isLoading: isEditingPartialSession } =
    useEditPartialSession({
      onSuccess: () => {
        queryClient.invalidateQueries(sessionsKeys.sessions.all());
      },
    });

  const showUnpublishSession = sessionStatus === SessionStatus.published;
  const showManageAttendance =
    sessionStatus === SessionStatus.finished ||
    sessionStatus === SessionStatus.published;

  const options: MenuListProps['options'] = [
    ...insertIf(showManageAttendance, {
      disabled: !sessionId,
      title: t('session.attendance.manage'),
      onClick: () =>
        navigate(sessionsRoutes.manageAttendance(sessionId), {
          state: { backRoute: `${location.pathname}${location.search}` },
        }),
    }),
    ...insertIf(showUnpublishSession, {
      disabled: isEditingPartialSession,
      title: t('general:deactivate'),
      onClick: () => {
        editPartialSession({
          sessionId,
          data: { status: SessionStatus.draft },
        });
      },
    }),
    {
      title: t('session.delete'),
      onClick: () => deleteSessionDialog.showModal({ sessionId }),
    },
  ];

  return (
    <>
      {deleteSessionDialog.modal}
      <TableCell
        sx={{ width: 60 }}
        align="right"
      >
        <MenuList
          options={options}
          position="right"
        />
      </TableCell>
    </>
  );
};
