import { type FC } from 'react';

import { IconChevronRight } from '@material-hu/icons/tabler';

import HuCardContainer from '@material-hu/components/design-system/CardContainer';
import HuListItem from '@material-hu/components/design-system/List/components/ListItem';

import { useAuth } from 'src/contexts/JWTContext';
import { getStateName } from 'src/pages/dashboard/serviceManagement/utils';
import { type TaskChild } from 'src/pages/dashboard/serviceManagement/types';
import { formatLocalizedDate } from 'src/utils/date';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { getInitials } from 'src/utils/userUtils';

import { getUserDisplayName } from '../../../utils';

import { getTaskPillType } from './TasksTab';

type TaskChildItemProps = {
  taskChild: TaskChild;
  onOpen: (taskChild: TaskChild) => void;
};

const TaskChildItem: FC<TaskChildItemProps> = ({ taskChild, onOpen }) => {
  const { t } = useLokaliseTranslation('service_management');
  const { user } = useAuth();

  const displayName = getUserDisplayName(taskChild.assignee, user, t);

  return (
    <HuCardContainer
      fullWidth
      padding={0}
      sx={{ mb: 2 }}
      onClick={() => onOpen(taskChild)}
    >
      <HuListItem
        text={{
          title: taskChild.name,
          description: t('subtasks.assigned_to', {
            agentName: displayName,
          }),
          copetin: t(`approvals.requested_at`, {
            date: formatLocalizedDate(taskChild.createdAt, {
              includeTime: true,
            }),
          }),
        }}
        avatar={{
          src: taskChild.assignee?.profilePicture,
          text: getInitials(displayName),
        }}
        sidePill={{
          label: t(getStateName(taskChild.state.name)),
          type: getTaskPillType(taskChild.state.name),
        }}
        action={{
          Icon: IconChevronRight,
          onClick: e => {
            e.stopPropagation();
            onOpen(taskChild);
          },
        }}
        sx={{
          '.MuiAvatar-root': { mr: 1 },
        }}
      />
    </HuCardContainer>
  );
};

export default TaskChildItem;
