import { lazy, Suspense } from 'react';

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

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

import { type PathStatusType } from 'src/pages/dashboard/Learning/Paths/types';
import { insertIf } from 'src/utils/arrayUtils';
import { useLokaliseTranslation } from 'src/utils/i18n';

const DeletePathModal = lazy(() => import('./DeletePathModal'));
const ChangePathStatusModal = lazy(() => import('./ChangePathStatusModal'));

type TableActionsProps = {
  pathId: number;
  pathStatus: PathStatusType;
  pathTitle: string;
};

const TableActions = ({ pathId, pathStatus, pathTitle }: TableActionsProps) => {
  const { t } = useLokaliseTranslation('learning');

  const {
    modal: deletePathModal,
    showModal: showDeletePathModal,
    closeModal: closeDeletePathModal,
  } = useModal(
    () => (
      <Suspense
        fallback={
          <Skeleton
            width={598}
            height={235}
          />
        }
      >
        <DeletePathModal
          pathId={pathId}
          onClose={closeDeletePathModal}
        />
      </Suspense>
    ),
    { onClick: e => e.stopPropagation() },
  );

  const {
    modal: changePathStatusModal,
    showModal: showChangePathStatusModal,
    closeModal: closeChangePathStatusModal,
  } = useModal(
    () => (
      <Suspense
        fallback={
          <Skeleton
            width={598}
            height={235}
          />
        }
      >
        <ChangePathStatusModal
          pathId={pathId}
          pathStatus={pathStatus}
          pathTitle={pathTitle}
          onClose={closeChangePathStatusModal}
        />
      </Suspense>
    ),
    { onClick: e => e.stopPropagation() },
  );

  const options: MenuListProps['options'] = [
    ...insertIf(pathStatus !== 'DRAFT', {
      title: t(
        pathStatus === 'ACTIVE' ? 'general:deactivate' : 'general:activate',
      ),
      onClick: showChangePathStatusModal,
    }),
    {
      title: t('path.delete.action'),
      onClick: () => showDeletePathModal({ pathId }),
    },
  ];

  return (
    <>
      {deletePathModal}
      {changePathStatusModal}
      <TableCell align="right">
        <MenuList
          options={options}
          position="right"
        />
      </TableCell>
    </>
  );
};

export default TableActions;
