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

import { insertIf } from 'src/utils/arrayUtils';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { LogEvents, logEvent } from 'src/utils/logging';

import { CategoryStatus, MAX_CATEGORIES_DEPTH } from '../../../constants';
import useActivateCategoryModal from '../../../hooks/useActivateCategoryModal';
import useDeactivateCategoryModal from '../../../hooks/useDeactivateCategoryModal';
import useDeleteCategoryModal from '../../../hooks/useDeleteCategoryModal';
import useManageCategoryDrawer from '../../../hooks/useManageCategoryDrawer';
import useUpdateCategoryStatus from '../../../hooks/useUpdateCategoryStatus';
import { type CategoryItem } from '../../../types';

type CategoriesTableRowActionsProps = {
  category: CategoryItem;
  depth?: number;
};

const CategoriesTableRowActions = ({
  category,
  depth = 1,
}: CategoriesTableRowActionsProps) => {
  const { t } = useLokaliseTranslation('learning');

  const { modal: deleteModal, showModal: showDeleteModal } =
    useDeleteCategoryModal();

  const { modal: deactivateModal, showModal: showDeactivateModal } =
    useDeactivateCategoryModal();

  const { modal: activateModal, showModal: showActivateModal } =
    useActivateCategoryModal();

  const { drawer: manageDrawer, showDrawer: showManageDrawer } =
    useManageCategoryDrawer(category);

  const { mutate: updateCategoryStatus } = useUpdateCategoryStatus();

  const handleActivate = () => {
    if (depth === 1) {
      // If the category is at the root level, activate it directly
      updateCategoryStatus({
        categoryId: category.id,
        status: CategoryStatus.ACTIVE,
      });
    } else {
      showActivateModal({ category });
    }
  };

  const handleManage = () => {
    logEvent(LogEvents.MANAGE_CATEGORY, { categoryId: category.id });
    showManageDrawer({});
  };

  const options: MenuListProps['options'] = [
    {
      title: t('general:delete'),
      onClick: () => showDeleteModal({ category }),
    },
    ...insertIf(category.status === CategoryStatus.ACTIVE, {
      title: t('general:deactivate'),
      onClick: () => showDeactivateModal({ category }),
    }),
    ...insertIf(category.status === CategoryStatus.INACTIVE, {
      title: t('general:activate'),
      onClick: handleActivate,
    }),
    ...insertIf(depth < MAX_CATEGORIES_DEPTH, {
      title: t('categories.manage.title'),
      onClick: handleManage,
    }),
  ];

  return (
    <>
      {deleteModal}
      {deactivateModal}
      {activateModal}
      {manageDrawer}
      <TableCell
        sx={{ width: 60 }}
        align="right"
      >
        <MenuList
          options={options}
          position="right"
        />
      </TableCell>
    </>
  );
};

export default CategoriesTableRowActions;
