import { FC, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useQuery } from 'react-query';
import { useParams, useMatch } from 'react-router-dom';

import Box from '@material-hu/mui/Box';
import CircularProgress from '@material-hu/mui/CircularProgress';

import useGeneralError from 'src/hooks/useGeneralError';
import { getApprovalWorkflow } from 'src/services/forms';
import { FormType } from 'src/types/forms';

import {
  ApprovalWorkflowHeader,
  ApprovalWorkflowContent,
  DialogAddComment,
} from 'src/components/dashboard/form/approvalWorkflow';
import { formKeys } from 'src/components/dashboard/form/queries';
import { formRoutes } from 'src/components/dashboard/form/routes';

const FormApprovalWorkflow: FC = () => {
  const [openModalApprove, setOpenModalApprove] = useState(false);
  const [openModalReject, setOpenModalReject] = useState(false);

  const { id } = useParams();
  const showGeneralError = useGeneralError();
  const { t } = useTranslation(['FORM', 'FORMS']);

  const viewAgent = useMatch(
    formRoutes.requests.approvalWorkflow(FormType.FORM, id),
  );

  const { data, isLoading } = useQuery(
    formKeys.formApprovalWorkflow(Number(id)),
    () => getApprovalWorkflow(id),
    {
      onError: err => showGeneralError(err, t('TICKETS:ERROR_LOADING_THREAD')),
    },
  );

  const formData = data ? data?.data : undefined;
  const lastStep = formData
    ? formData.steps[formData.steps.length - 1]
    : undefined;

  const handleApprove = () => {
    setOpenModalApprove(true);
  };
  const handleReject = () => {
    setOpenModalReject(true);
  };

  return (
    <>
      {formData && !isLoading && (
        <Box
          sx={{
            backgroundColor: 'background.default',
            display: 'flex',
            flexDirection: 'column',
            flexGrow: 1,
            height: '100%',
            overflow: 'scroll',
          }}
        >
          <ApprovalWorkflowHeader
            {...formData}
            lastStep={lastStep}
            handleApprove={handleApprove}
            handleReject={handleReject}
            viewAgent={viewAgent}
          />
          <Box
            sx={{
              flexGrow: 1,
            }}
          >
            <ApprovalWorkflowContent {...formData} />
          </Box>
        </Box>
      )}
      {isLoading && (
        <Box sx={{ textAlign: 'center', my: 1 }}>
          <CircularProgress />
        </Box>
      )}
      <DialogAddComment
        approveForm
        open={openModalApprove}
        title={t('FORMS:TITLE_APPROVE_FORM')}
        handleCancel={() => setOpenModalApprove(false)}
        {...formData}
      />
      <DialogAddComment
        rejectForm
        open={openModalReject}
        title={t('FORMS:TITLE_REJECT_FORM')}
        handleCancel={() => setOpenModalReject(false)}
        {...formData}
      />
    </>
  );
};

export default FormApprovalWorkflow;
