import { useEffect } from 'react';
import { FormProvider } from 'react-hook-form';
import { useNavigate } from 'react-router-dom';

import Stack from '@material-hu/mui/Stack';

import FormFooter from '@material-hu/components/composed-components/dynamic-forms/components/FormFooter';
import FormInputsCatalog from '@material-hu/components/composed-components/dynamic-forms/components/FormInputsCatalog';
import useDynamicFormAnswer from '@material-hu/components/composed-components/dynamic-forms/hooks/useDynamicFormAnswer';
import { DynamicFormAnswer } from '@material-hu/components/composed-components/dynamic-forms/types';
import TaskFocusHeader from '@material-hu/components/design-system/Header/TaskFocus';
import Spinner from '@material-hu/components/design-system/ProgressIndicators/Spinner';

import useHuGoTheme from 'src/hooks/useHuGoTheme';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { getDynamicFormAnswer } from '../../services';

export type DynamicFormResultsProps = {
  answerId: number;
  answerToken: string;
  tag: string;
};

const DynamicFormResults = ({
  answerId,
  answerToken,
  tag,
}: DynamicFormResultsProps) => {
  const { t } = useLokaliseTranslation(['general']);
  const HugoThemeProvider = useHuGoTheme();
  const navigate = useNavigate();

  const methods = useDynamicFormAnswer<DynamicFormAnswer>({
    errorTexts: {
      required: t('general:required_field'),
    },
    getAnswerFn: async () => {
      const response = await getDynamicFormAnswer({
        tag,
        answerId,
        answerToken,
      });

      return response as unknown as DynamicFormAnswer;
    },
  });

  const onNextPress = () => {
    if (!methods.formAnswer?.sections.length) return;

    if (methods.isOnLastSection) return navigate(-1);

    methods.changeStep({});
  };

  const onBackPress = () => {
    methods.changeStep({ isBackStep: true });
  };

  useEffect(() => {
    if (answerId && answerToken && tag) {
      methods.getAnswerMutation.mutate();
    }
  }, [answerId, answerToken, tag]);

  return (
    <HugoThemeProvider>
      <FormProvider {...methods.form}>
        <Stack
          sx={{
            backgroundColor: theme =>
              theme.palette.new.background.layout.default,
            minHeight: '100%',
            width: '100%',
          }}
        >
          <TaskFocusHeader
            title={methods?.formTitle || ''}
            onClose={() => navigate(-1)}
          />
          <Stack sx={{ flex: 1 }}>
            <Stack
              sx={{
                flex: 1,
                maxWidth: 'lg',
                mx: 'auto',
                width: '100%',
                py: 5,
                px: 3,
                pb: 10,
              }}
            >
              {methods.isLoading && (
                <Stack sx={{ justifyContent: 'center', alignItems: 'center' }}>
                  <Spinner />
                </Stack>
              )}
              {!methods.isLoading && methods.currentSection && (
                <FormInputsCatalog
                  section={methods.currentSection}
                  isFrozen={methods.isFrozen}
                />
              )}
            </Stack>
          </Stack>
          <FormFooter
            sx={{
              backgroundColor: theme =>
                theme.palette.new.background.layout.tertiary,
              position: 'sticky',
              p: 2,
            }}
            nextButton={{
              children: methods.isOnLastSection
                ? t('general:back_to_start')
                : t('general:next'),
              onClick: onNextPress,
              disabled: methods.getAnswerMutation.isLoading,
            }}
            backButton={{
              children: t('general:back'),
              onClick: onBackPress,
              disabled:
                methods.getAnswerMutation.isLoading || methods.isOnFirstSection,
            }}
          />
        </Stack>
      </FormProvider>
    </HugoThemeProvider>
  );
};

export default DynamicFormResults;
