import { type FC } from 'react';
import { useNavigate } from 'react-router-dom';

import { type TFunction } from 'i18next';
import Box from '@material-hu/mui/Box';
import Chip from '@material-hu/mui/Chip';
import { grey } from '@material-hu/mui/colors';
import DividerUI from '@material-hu/mui/Divider';
import ListItem from '@material-hu/mui/ListItem';
import ListItemText from '@material-hu/mui/ListItemText';
import Stack from '@material-hu/mui/Stack';
import { styled } from '@material-hu/mui/styles';
import Typography from '@material-hu/mui/Typography';

import { clearChatNotifications } from 'src/services/chats';
import { clearFormChatNotifications } from 'src/services/forms';
import { type ChatListItem } from 'src/types/chats';
import { FormType, InputType } from 'src/types/forms';
import { formatRelativeDate } from 'src/utils/date';
import {
  getBackgroundColor,
  getCorrectStatus,
  getInfoText,
  getLabel,
} from 'src/utils/form';
import { useLokaliseTranslation } from 'src/utils/i18n';

import Badge from 'src/components/Badge';
import FormChatAvatar from 'src/components/dashboard/chat/ChatAvatar/FormChatAvatar';
import { removeFormChatNotification } from 'src/components/dashboard/form/queries';
import { formRoutes } from 'src/components/dashboard/form/routes';

const Status = styled(Chip)(({ theme }) => ({
  display: 'block',
  maxWidth: 'max-content',
  width: '100%',
  marginBottom: theme.spacing(0.5),
  color: theme.palette.new.text.neutral.inverted,
  overflow: 'hidden',
  textOverflow: 'ellipsis',
  '&.approved': {
    backgroundColor: theme.palette.success.main,
  },
  '&.rejected': {
    backgroundColor: theme.palette.error.main,
  },
  '&.cancelled': {
    backgroundColor: theme.palette.warning.main,
  },
}));

const Info = styled(Box)({
  display: 'flex',
  flexDirection: 'column',
  alignSelf: 'flex-start',
  marginTop: '6px',
  marginBottom: '6px',
});

const Divider = styled(DividerUI)(({ theme }) => ({
  marginLeft: theme.spacing(11),
  '&:last-child': {
    display: 'none',
  },
}));

export type FromListCompletedItemProps = {
  formId: number;
  chatId: number;
  pictureUrl: string;
  title: string;
  type: string;
  lastMessage?: any;
  unreadMessages?: number;
  needApproval: boolean;
  approvalStatus: string;
  withInProgressStatus?: boolean;
  formChat?: ChatListItem;
  isAgent?: boolean;
  lastStepOfResponsible?: {
    approvalStatus: string;
  };
};

export const FromListCompletedItem: FC<FromListCompletedItemProps> = props => {
  const {
    pictureUrl,
    formId,
    chatId,
    type,
    title,
    lastMessage,
    unreadMessages,
    needApproval,
    approvalStatus,
    withInProgressStatus,
    formChat,
    isAgent = false,
    lastStepOfResponsible,
  } = props;

  const { t } = useLokaliseTranslation('forms');
  const navigate = useNavigate();
  const unreadMessagesCount = unreadMessages || 0;

  const getMessage = () => {
    if (lastMessage?.type === InputType.INFO) {
      return getInfoText(lastMessage?.text);
    }
    return lastMessage?.text;
  };

  const navigateToFormDetail = () => {
    if (unreadMessagesCount > 0) {
      removeFormChatNotification();
      chatId
        ? clearChatNotifications(chatId)
        : clearFormChatNotifications(formId);
    }

    if (isAgent && chatId) {
      return navigate(formRoutes.requests.detail(type, chatId));
    }

    if (isAgent && !chatId) {
      return navigate(formRoutes.requests.approvalWorkflow(type, formId));
    }

    if (needApproval) {
      return navigate(formRoutes.form.approvalWorkflow(type, formId));
    }

    if (!needApproval) {
      return navigate(formRoutes.form.chat(type, chatId));
    }
  };

  const correctStatus = getCorrectStatus(
    false,
    approvalStatus,
    lastStepOfResponsible,
  );

  return (
    <>
      <ListItem
        button
        onClick={navigateToFormDetail}
      >
        <Stack>
          <FormChatAvatar
            pictureUrl={pictureUrl}
            sx={{ ml: '3px' }}
          />
          <Typography
            component="span"
            color="textSecondary"
            variant="body2"
            mt={1}
          >
            {`#${formId}`}
          </Typography>
        </Stack>
        <ListItemText
          primary={
            <Stack>
              {title}
              {withInProgressStatus && formChat?.status && (
                <Chip
                  label={t(formChat?.status!)}
                  color="secondary"
                  size="small"
                  sx={{ backgroundColor: grey[500], width: 'fit-content' }}
                />
              )}
              {type === FormType.FORM && !withInProgressStatus && (
                <Status
                  color="primary"
                  label={getLabel(needApproval, correctStatus, t as TFunction)}
                  size="small"
                  className={correctStatus?.toLowerCase()}
                  sx={{
                    backgroundColor: getBackgroundColor(needApproval, false),
                  }}
                />
              )}
            </Stack>
          }
          primaryTypographyProps={{
            color: 'textPrimary',
            noWrap: true,
            variant: 'subtitle2',
          }}
          secondary={getMessage()}
          secondaryTypographyProps={{
            color: 'textSecondary',
            noWrap: true,
            variant: 'body2',
          }}
        />
        <Info>
          <Typography
            color="textSecondary"
            variant="body2"
          >
            {formatRelativeDate(new Date(lastMessage?.createdAt))}
          </Typography>
          {unreadMessagesCount > 0 && (
            <Typography
              color="textPrimary"
              variant="subtitle2"
              textAlign="end"
            >
              <Badge count={unreadMessagesCount} />
            </Typography>
          )}
        </Info>
      </ListItem>
      <Divider />
    </>
  );
};

export default FromListCompletedItem;
