import { type FC } from 'react';

import { IconChevronDown } from '@material-hu/icons/tabler';
import Box from '@material-hu/mui/Box';
import IconButton from '@material-hu/mui/IconButton';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

import { useAuth } from 'src/contexts/JWTContext';
import { type Task } from 'src/pages/dashboard/serviceManagement/types';
import { useLokaliseTranslation } from 'src/utils/i18n';

import UserTooltip from '../../servicePortal/requestedDetails/components/Information/UserTooltip';
import { getUserDisplayName } from '../../utils';

type Props = {
  index: number;
  task: Task;
  onOpenSingleReassign?: (task: Task, index: number) => void;
  showButton?: boolean;
};

const AgentColumn: FC<Props> = ({
  index,
  task,
  onOpenSingleReassign,
  showButton,
}) => {
  const { t } = useLokaliseTranslation('service_management');
  const { user } = useAuth();
  return (
    <Stack
      id={`id-agent-row-${index}`}
      sx={{
        flexDirection: 'row',
        alignItems: 'center',
        gap: 0.5,
        width: '100%',
        position: 'relative',
        pr: !showButton ? 3.25 : 0,
      }}
      onClick={e => {
        if (!showButton) {
          return;
        }
        e.stopPropagation();
        onOpenSingleReassign?.(task, index);
      }}
    >
      {task.assignee && (
        <Box sx={{ minWidth: 0, overflow: 'hidden' }}>
          <UserTooltip
            user={task.assignee}
            tooltipProps={{
              direction: 'top',
            }}
          >
            <Typography
              variant="globalS"
              sx={{
                whiteSpace: 'nowrap',
                overflow: 'hidden',
                textOverflow: 'ellipsis',
                display: 'block',
                '&:hover': {
                  textDecoration: 'underline',
                },
              }}
            >
              {getUserDisplayName(task.assignee, user!, t)}
            </Typography>
          </UserTooltip>
        </Box>
      )}
      {!task.assignee && (
        <Typography
          variant="globalS"
          sx={{
            minWidth: 0,
            whiteSpace: 'nowrap',
            overflow: 'hidden',
            textOverflow: 'ellipsis',
          }}
        >
          {t('unassigned')}
        </Typography>
      )}
      {showButton && (
        <IconButton
          sx={{
            py: 0,
            pl: 0.5,
            pr: 0,
          }}
          onClick={e => {
            e.stopPropagation(); // Prevent triggering row click
            onOpenSingleReassign?.(task, index);
          }}
        >
          <IconChevronDown size={18} />
        </IconButton>
      )}
    </Stack>
  );
};

export default AgentColumn;
