import { FC } from 'react';

import qs from 'qs';

import ScheduleIcon from '@material-hu/icons/material/Schedule';
import Box from '@material-hu/mui/Box';
import Tooltip from '@material-hu/mui/Tooltip';
import Typography from '@material-hu/mui/Typography';

import { ChatStatus } from 'src/types/chats';
import { FormItemResponse } from 'src/types/forms';
import { getColorByTime, getResolutionTime } from 'src/utils/date';
import { getDueDate } from 'src/utils/form';
import { useLokaliseTranslation } from 'src/utils/i18n';

export type FormRequestResolutionTimeProps = Pick<
  FormItemResponse,
  'lastFilledStep'
> & {};

export const FormRequestResolutionTime: FC<
  FormRequestResolutionTimeProps
> = props => {
  const { lastFilledStep } = props;
  const { t } = useLokaliseTranslation('forms');
  const params = qs.parse(location.search, { ignoreQueryPrefix: true });
  const tabSelected =
    Object.keys(params)[0]?.toLocaleUpperCase() || ChatStatus.UNASSIGNED;

  const isUnassigned = tabSelected === ChatStatus.UNASSIGNED;
  const isAssigned = tabSelected === ChatStatus.ASSIGNED;
  const isClosed = tabSelected === ChatStatus.CLOSED;

  const createdAt = new Date(lastFilledStep?.assignedDatetime);
  const dueDate = new Date(
    getDueDate(isUnassigned, isAssigned, lastFilledStep),
  );

  const showResolutionTime =
    (isAssigned && lastFilledStep?.reviewDatetimeLimit) ||
    (isUnassigned && lastFilledStep?.assignedDatetimeLimit) ||
    (isClosed && lastFilledStep?.reviewDatetime);

  const formattedResolutionTime = getResolutionTime(
    dueDate,
    isClosed ? createdAt : undefined,
  );

  return (
    <>
      {showResolutionTime && (
        <Tooltip
          title={t(`REMAINING_TIME_INFORMATION_${tabSelected}`)}
          componentsProps={{
            tooltip: {
              sx: {
                p: '4px 8px',
                borderRadius: '4px',
              },
            },
          }}
        >
          <Box
            sx={{
              display: 'flex',
              flexDirection: 'row',
              alignItems: 'center',
              gap: 0.5,
              justifyContent: 'end',
              width: 'max-content',
            }}
          >
            <ScheduleIcon
              fontSize="medium"
              color={getColorByTime(createdAt, dueDate, tabSelected)}
            />
            <Typography
              color="textSecondary"
              variant="body2"
            >
              {formattedResolutionTime}
            </Typography>
          </Box>
        </Tooltip>
      )}
    </>
  );
};

export default FormRequestResolutionTime;
