import { type FC, useEffect, useRef, useState } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';

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

import { useMassiveAssign } from 'src/pages/dashboard/forms/MassiveAssignContext';
import {
  CLOSED,
  type FormItemResponse,
  FormPossibleStatus,
  FormType,
} from 'src/types/forms';
import { formatRelativeDate } from 'src/utils/date';
import { getBackgroundColor, getCorrectStatus, 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 RegularChatName from 'src/components/dashboard/chat/ChatName/RegularChatName';
import FormRequestResolutionTime from 'src/components/dashboard/form/FormRequestResolutionTime';
import FormRequestSLA from 'src/components/dashboard/form/FormRequestSLA';
import { formRoutes } from 'src/components/dashboard/form/routes';

const Item = styled(ListItemButton)(({ theme }) => ({
  '&.Mui-selected': {
    boxShadow: `inset 4px 0px 0px ${theme.palette.primary.main}`,
  },
}));

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 FormRequestItemProps = FormItemResponse & {
  active?: boolean;
  isBulkAssign?: boolean;
};

export const FormRequestItem: FC<FormRequestItemProps> = props => {
  const {
    pictureUrl,
    formId,
    chatId,
    formChat,
    stepId,
    type,
    title,
    lastMessage,
    unreadMessages,
    needApproval,
    approvalStatus,
    active = false,
    isBulkAssign = false,
    creator,
    withInProgressStatus,
    lastFilledStep,
    lastStepOfResponsible,
  } = props;

  const { addItem, removeItem, isSelecting, reachedLimit, isChecked } =
    useMassiveAssign();

  const { t } = useLokaliseTranslation('forms');

  const navigate = useNavigate();
  const { search } = useLocation();

  const textRef = useRef<HTMLParagraphElement>(null);
  const [isTextOverflowed, setIsTextOverflowed] = useState(false);

  useEffect(() => {
    // Verifica si el texto está truncado con elipsis
    if (textRef.current) {
      setIsTextOverflowed(
        textRef.current.scrollWidth > textRef.current.clientWidth,
      );
    }
  }, [title]);

  const navigateToFormDetail = () => {
    const pathname = chatId
      ? formRoutes.requests.detail(type, chatId)
      : formRoutes.requests.approvalWorkflow(type, formId);

    navigate({ pathname, search });
  };

  const showCheckBox =
    isSelecting && (isBulkAssign || needApproval) && approvalStatus !== CLOSED;

  const disableCheckBox = reachedLimit && !isChecked(formId);

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

  const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const item = { chatId, formId, stepId };
    event.target.checked ? addItem(item) : removeItem(formId);
  };

  return (
    <Box sx={{ display: 'flex', direction: 'row' }}>
      {showCheckBox && (
        <Box sx={{ alignSelf: 'center' }}>
          <Tooltip
            title={t('BULK_MAX_REACH')}
            disableHoverListener={!disableCheckBox}
          >
            <span>
              <Checkbox
                disabled={disableCheckBox}
                onChange={handleChange}
                sx={{ borderRadius: 0 }}
                aria-label="select-form"
              />
            </span>
          </Tooltip>
        </Box>
      )}
      <Item
        onClick={navigateToFormDetail}
        selected={active}
      >
        <Stack
          alignItems="center"
          marginRight="18px"
        >
          <FormChatAvatar
            pictureUrl={pictureUrl}
            sx={{ mr: 0, mb: 1 }}
          />
          <Typography
            color="primary"
            variant="subtitle2"
          >
            {`#${formId}`}
          </Typography>
        </Stack>
        <ListItemText
          primary={
            <>
              <Tooltip
                title={title}
                disableHoverListener={!isTextOverflowed}
                componentsProps={{
                  tooltip: {
                    sx: {
                      borderRadius: '4px',
                      mt: '0 !important',
                    },
                  },
                }}
              >
                <Typography
                  ref={textRef}
                  variant="body2"
                  noWrap
                  sx={{
                    width: '100%',
                  }}
                >
                  {title}
                </Typography>
              </Tooltip>
              {type === FormType.FORM && (
                <>
                  <RegularChatName
                    otherUser={creator}
                    withLink={false}
                    color="info.dark"
                    sx={{ width: '100%', mb: 0.5 }}
                  />
                  {!withInProgressStatus && (
                    <Status
                      color="primary"
                      label={getLabel(
                        needApproval,
                        correctStatus,
                        t as TFunction,
                      )}
                      size="small"
                      className={correctStatus.toLowerCase()}
                      sx={{
                        backgroundColor: getBackgroundColor(needApproval, true),
                      }}
                    />
                  )}
                  {withInProgressStatus && (
                    <Chip
                      label={t(formChat?.status || '')}
                      color="secondary"
                      size="small"
                      sx={{ backgroundColor: grey[500], width: 'fit-content' }}
                    />
                  )}
                </>
              )}
            </>
          }
          primaryTypographyProps={{
            color: 'textPrimary',
            noWrap: true,
            variant: 'subtitle2',
            sx: {
              display: 'flex',
              flexDirection: 'column',
              alignItems: 'flex-start',
              maxWidth: 'max-content',
            },
          }}
        />
        <Info>
          <Typography
            color="textSecondary"
            variant="body2"
            alignSelf="end"
          >
            {formatRelativeDate(new Date(lastMessage?.createdAt))}
          </Typography>
          {unreadMessages > 0 && (
            <Typography
              color="textPrimary"
              variant="subtitle2"
              textAlign="end"
            >
              <Badge count={unreadMessages} />
            </Typography>
          )}
          {!withInProgressStatus && (
            <FormRequestResolutionTime lastFilledStep={lastFilledStep} />
          )}
          {withInProgressStatus && (
            <Stack sx={{ gap: 1, mt: 1 }}>
              {(formChat?.status === FormPossibleStatus.UNASSIGNED ||
                formChat?.status === FormPossibleStatus.ASSIGNED) && (
                <FormRequestSLA
                  sla={formChat?.timeToFirstResponseSlaTimer}
                  status={formChat?.status}
                />
              )}
              <FormRequestSLA
                sla={formChat?.timeToResolutionSlaTimer}
                status={formChat?.status}
              />
            </Stack>
          )}
        </Info>
      </Item>
      <Divider />
    </Box>
  );
};

export default FormRequestItem;
