import { type FC, useState } from 'react';
import { useQueryClient } from 'react-query';
import { useNavigate } from 'react-router-dom';

import DescriptionIcon from '@material-hu/icons/material/Description';
import DownloadIcon from '@material-hu/icons/material/Download';
import EditIcon from '@material-hu/icons/material/Edit';
import Box from '@material-hu/mui/Box';
import ButtonBase from '@material-hu/mui/ButtonBase';
import CircularProgress from '@material-hu/mui/CircularProgress';
import Container from '@material-hu/mui/Container';
import { styled } from '@material-hu/mui/styles';
import Typography from '@material-hu/mui/Typography';

import useGeneralError from 'src/hooks/useGeneralError';
import { fetchFormCompletedPdfBlob } from 'src/services/forms';
import { type FormListItem, FormStepType } from 'src/types/forms';
import { openBlob } from 'src/utils/files';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { useTranslation } from 'src/components/dashboard/chat/i18n';
import { formKeys } from 'src/components/dashboard/form/queries';
import { formRoutes } from 'src/components/dashboard/form/routes';

export type ChatShowFormProps = {
  formData: FormListItem;
  isResponsible?: boolean;
};

const ButtonsContainer = styled(Box)(() => ({
  display: 'flex',
  flexDirection: 'row',
  paddingBottom: '10px',
}));

const Message = styled(Container)(() => ({
  padding: '8px 16px',
  textAlign: 'center',
  fontSize: '37px',
  '& svg': {
    color: '#333333',
  },
}));

const MessageButton = styled(ButtonBase)(() => ({
  borderRadius: '16px',
  backgroundColor: '#3656C3',
  color: 'inherit',
  display: 'flex',
  flexDirection: 'column',
}));

const FooterText = styled(Container)(({ theme }) => ({
  backgroundColor: '#333333',
  borderBottomLeftRadius: '16px',
  borderBottomRightRadius: '16px',
  color: 'white',
  padding: theme.spacing(1),
}));

export const ChatShowForm: FC<ChatShowFormProps> = props => {
  const { formData, isResponsible = false } = props;

  const [isLoadingPdf, setIsLoadingPdf] = useState<boolean>(false);

  const navigate = useNavigate();
  const queryClient = useQueryClient();
  const { t } = useTranslation();
  const showGeneralError = useGeneralError();

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

  const { id, templateId, type, canEditAnswer, stepsType } = formData;

  const isPdfAnswer = stepsType === FormStepType.FILE;

  const handleShowForm = () => {
    navigate(
      isPdfAnswer
        ? formRoutes.form.pdfCompleted(type, templateId, id)
        : formRoutes.form.completed(type, templateId, id),
    );
  };

  const handleEditForm = () =>
    navigate(formRoutes.form.edit(type, templateId, id));

  const handleDownloadPdf = async () => {
    try {
      setIsLoadingPdf(true);

      const pdfData = await queryClient.fetchQuery(
        formKeys.pdf.blob(templateId, id),
        () => fetchFormCompletedPdfBlob(templateId, id),
      );

      const { blob = null, blobUrl = null } = pdfData || {};

      openBlob(blob, blobUrl);
    } catch (err) {
      showGeneralError(err, formsT('ERROR_LOADING_PDF_REPORT'));
    } finally {
      setIsLoadingPdf(false);
    }
  };

  return (
    <ButtonsContainer>
      {canEditAnswer && !isResponsible && (
        <MessageButton
          onClick={handleEditForm}
          sx={{ mr: 2 }}
        >
          <Message>
            <EditIcon fontSize="large" />
          </Message>
          <FooterText>
            <Typography variant="subtitle2">{t('EDIT_MY_ANSWER')}</Typography>
          </FooterText>
        </MessageButton>
      )}
      <MessageButton
        onClick={handleShowForm}
        sx={{ mr: 2 }}
      >
        <Message>
          <DescriptionIcon fontSize="large" />
        </Message>
        <FooterText>
          <Typography variant="subtitle2">
            {t(isResponsible ? 'SEE_ANSWER' : 'SEE_MY_ANSWER')}
          </Typography>
        </FooterText>
      </MessageButton>
      {!isPdfAnswer && (
        <MessageButton
          onClick={handleDownloadPdf}
          disabled={isLoadingPdf}
        >
          <Message>
            {isLoadingPdf ? (
              <CircularProgress />
            ) : (
              <DownloadIcon fontSize="inherit" />
            )}
          </Message>
          <FooterText>
            <Typography variant="subtitle2">{t('DOWNLOAD_ANSWER')}</Typography>
          </FooterText>
        </MessageButton>
      )}
    </ButtonsContainer>
  );
};

export default ChatShowForm;
