import { useEffect } from 'react';

import { useLocation, useNavigate } from 'react-router-dom';

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

import { appearFromBottom } from '@material-hu/utils/animations';

import DynamicFormContextProvider from '@material-hu/components/composed-components/dynamic-forms/components/DynamicFormContextProvider';
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 FormSectionSkeleton from '@material-hu/components/composed-components/dynamic-forms/components/FormSectionSkeleton';
import FormSuccessScreen from '@material-hu/components/composed-components/dynamic-forms/components/FormSuccessScreen';
import useDynamicForm from '@material-hu/components/composed-components/dynamic-forms/hooks/useDynamicForm';
import { SectionEvent } from '@material-hu/components/composed-components/dynamic-forms/types';
import TaskFocusHeader from '@material-hu/components/design-system/Header/TaskFocus';
import { useSnackbar } from '@material-hu/components/design-system/Snackbar';

import useHuGoTheme from 'src/hooks/useHuGoTheme';
import { uploadFiles } from 'src/services/attachments';
import { useLokaliseTranslation } from 'src/utils/i18n';
import {
  getDynamicFormProgress,
  updateDynamicFormProgression,
} from 'src/components/dynamicForms/services';
import { DynamicFormResponseExtended } from 'src/components/dynamicForms/types';

import { useEmployeeLifecycleIds } from '../../../hooks/useEmployeeLifecycleIds';
import { useGetJourneyTask } from '../../../hooks/useGetJourneyTask';
import { useMarkTaskAsDone } from '../../../hooks/useMarkTaskAsDone';
import { employeeLifecycleRoutes } from '../../../routes';
import { JourneyTaskType } from '../../../types';

type FormTaskLocationState = {
  journeyId: number;
  stepId: number;
};

const FormTask = () => {
  const HugoThemeProvider = useHuGoTheme();

  const { t } = useLokaliseTranslation([
    'employee_lifecycle',
    'service_management',
    'validations',
  ]);
  const { progressionId, tag, taskId } = useEmployeeLifecycleIds();
  const { enqueueSnackbar } = useSnackbar();
  const location = useLocation();
  const state = location.state as FormTaskLocationState;
  const navigate = useNavigate();
  const { task } = useGetJourneyTask(taskId ?? null);

  const onCloseForm = () => {
    if (!state) return navigate(-1);

    const backRoute = employeeLifecycleRoutes.journeys.task(
      state.journeyId,
      state.stepId,
      taskId!,
    );

    navigate(backRoute);
  };

  const { mutateAsync: markAsDone, isLoading: isLoadingMarkAsDone } =
    useMarkTaskAsDone(task);

  const onCompleteForm = async (formAnswerId: number | null) => {
    if (!formAnswerId || !taskId || !progressionId) {
      enqueueSnackbar({
        title: t('general:we_had_an_error'),
        description: t('general:error_description'),
        variant: 'error',
      });
      return;
    }

    markAsDone({
      taskId,
      data: {
        type: JourneyTaskType.FORM,
        progressionId,
        answerId: formAnswerId.toString(),
      },
    });

    unsavedWarningDialog?.disableUnsavedWarning();
  };

  const methods = useDynamicForm<DynamicFormResponseExtended>({
    onCompleteForm: (formAnswerId?: number | null) => {
      if (!formAnswerId) throw new Error('Form answer ID is missing');
      onCompleteForm(formAnswerId);
    },
    getProgressionFn: async () => {
      if (!progressionId || !tag)
        throw new Error('Progression ID or tag is missing');

      const response = await getDynamicFormProgress({
        progressionId,
        tag,
      });
      // Cast to DynamicFormResponseExtended for compatibility with material-hu
      return response as DynamicFormResponseExtended;
    },
    updateProgressionFn: async ({ body }) => {
      if (!progressionId || !tag)
        throw new Error('Progression ID or tag is missing');

      const response = await updateDynamicFormProgression({
        body,
        progressionId,
        tag,
      });
      // Cast to DynamicFormResponseExtended for compatibility with material-hu
      return response as DynamicFormResponseExtended;
    },
    errorTexts: {
      required: t('general:required_field'),
      invalidPhone: t('validations:invalid_phone_number'),
    },
  });

  const unsavedWarningDialog = useUnsavedWarningDialog({
    title: t('general:unsaved_changes.title'),
    description: t('general:unsaved_changes.description'),
    primaryButtonText: t('general:cancel'),
    secondaryButtonText: t('general:unsaved_changes.confirm'),
  });

  useEffect(() => {
    if (progressionId && tag) {
      methods.getProgressionMutation.mutate();
    }
  }, [progressionId, tag]);

  if (methods.isInitializingForm) {
    return <FormSectionSkeleton />;
  }

  return (
    <HugoThemeProvider>
      {unsavedWarningDialog.modal}
      <DynamicFormContextProvider
        {...methods}
        isLoading={methods.isLoading || isLoadingMarkAsDone}
      >
        <Stack
          sx={{
            minHeight: '100vh',
            backgroundColor: theme =>
              theme.palette.new.background.layout.default,
          }}
        >
          <TaskFocusHeader
            title={methods.formTitle ?? ''}
            onClose={onCloseForm}
            slotProps={{
              root: {
                position: 'sticky',
                top: 0,
                zIndex: 1000,
              },
            }}
          />
          {methods.shouldShowFormSuccess && (
            <Stack
              sx={{
                flex: 1,
                alignItems: 'center',
                justifyContent: 'center',
              }}
            >
              <FormSuccessScreen
                action={{
                  children: t('questionnaire_form_task.success_form.button'),
                  onClick: onCloseForm,
                }}
                title={t('questionnaire_form_task.success_form.title')}
                description={t(
                  'questionnaire_form_task.success_form.description',
                )}
              />
            </Stack>
          )}
          {methods.shouldShowFormBody && (
            <Stack
              sx={{
                flex: 1,
                p: 3,
                pt: 5,
                maxWidth: theme => theme.breakpoints.values.lg,
                mx: 'auto',
                width: '100%',
                animation: `${appearFromBottom} 125ms ease-in-out backwards`,
              }}
              key={methods.formResponse?.currentSection}
            >
              <FormInputsCatalog.Connected
                key={methods.formResponse?.currentSection ?? ''}
                sx={{
                  ...(methods.isLoading
                    ? { opacity: 0.5, pointerEvents: 'none' }
                    : {}),
                }}
                slotProps={{
                  fields: {
                    TEXT: {
                      placeholder: t('service_management:text_placeholder'),
                      maxLength: 250,
                    },
                    SIGNATURE: {
                      signProps: {
                        uploadFn: uploadFiles,
                      },
                      buttonProps: {
                        children: t('general:sign'),
                      },
                      deleteButtonProps: {
                        children: t('general:delete'),
                      },
                      editButtonProps: {
                        children: t('general:edit'),
                      },
                    },
                    FILE: {
                      uploadFn: uploadFiles,
                    },
                  },
                }}
              />
            </Stack>
          )}
          {methods.shouldShowFormFooter && (
            <FormFooter
              sx={{
                zIndex: 10,
                backgroundColor: theme =>
                  theme.palette.new.background.layout.tertiary,
              }}
              nextButton={{
                onClick: () => methods.submitSection(),
                children: t('general:continue'),
                disabled: methods.isLoading || methods.isFrozen,
                loading:
                  methods.isLoading &&
                  methods.updateProgressionMutation.variables?.body
                    .sectionEvent === SectionEvent.Complete,
              }}
              backButton={{
                onClick: () => methods.changeStep({ isBackStep: true }),
                children: t('general:back'),
                disabled:
                  methods.isOnFirstSection ||
                  methods.isFrozen ||
                  methods.isLoading,
                loading:
                  methods.isLoading &&
                  methods.updateProgressionMutation.variables?.body
                    .sectionEvent === SectionEvent.Back,
              }}
            />
          )}
        </Stack>
      </DynamicFormContextProvider>
    </HugoThemeProvider>
  );
};

export default FormTask;
