import { IconCircleCheck, IconCircleX } from '@material-hu/icons/tabler';

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

import { SessionStatus } from 'src/pages/dashboard/Learning/Sessions/constants';
import { useUpdateSessionAttendance } from 'src/pages/dashboard/Learning/Sessions/hooks/useUpdateSessionAttendance';
import {
  type SessionAttendance,
  type SessionStatusType,
} from 'src/pages/dashboard/Learning/Sessions/types';
import { insertIf } from 'src/utils/arrayUtils';
import { useLokaliseTranslation } from 'src/utils/i18n';

type TableActionsProps = {
  sessionStatus?: SessionStatusType;
  sessionId?: number;
  collaborator: SessionAttendance;
};

export const TableActions = ({
  sessionStatus,
  sessionId,
  collaborator,
}: TableActionsProps) => {
  const { t } = useLokaliseTranslation('learning');
  if (!sessionId || sessionStatus !== SessionStatus.finished) return null;

  const showMarkAsPresent =
    collaborator.assisted === null || !collaborator.assisted;
  const showMarkAsAbsent =
    collaborator.assisted === null || collaborator.assisted;

  const {
    mutate: updateSessionAttendance,
    isLoading: isUpdatingSessionAttendance,
  } = useUpdateSessionAttendance(sessionId);

  const options: MenuListProps['options'] = [
    ...insertIf(showMarkAsPresent, {
      title: t('session.attendance.mark_as_present'),
      disabled: isUpdatingSessionAttendance,
      Icon: IconCircleCheck,
      onClick: () =>
        updateSessionAttendance({
          userIds: [collaborator.userId],
          assisted: true,
        }),
    }),
    ...insertIf(showMarkAsAbsent, {
      title: t('session.attendance.mark_as_absent'),
      disabled: isUpdatingSessionAttendance,
      Icon: IconCircleX,
      onClick: () =>
        updateSessionAttendance({
          userIds: [collaborator.userId],
          assisted: false,
        }),
    }),
  ];

  return (
    <TableCell padding="checkbox">
      <MenuList
        aria-label={`${t('session.attendance.mark_as_present_or_absent')} ${collaborator.fullName}`}
        position="right"
        size="small"
        options={options}
        slotProps={{
          menu: {
            sx: { '& .MuiAvatar-root': { width: '32px', height: '32px' } },
          },
        }}
      />
    </TableCell>
  );
};
