import { FormProvider, useForm } from 'react-hook-form';
import { useParams } from 'react-router';

import useHuGoTheme from 'src/hooks/useHuGoTheme';
import { type FormAttributes, type QuestionSubmitData } from 'src/types/forms';

import { FormFileUploadProvider } from '../forms/FormFileUploadContext';

import SurveyCompletionForm from './components/SurveyCompletionForm';
import useSurveyCompletionAndEdit from './hooks/useSurveyCompletionAndEdit';

const SurveyCompletion = () => {
  const { id, templateId, answerId } = useParams();
  const HugoThemeProvider = useHuGoTheme();
  const form = useForm({});

  const {
    templateInfo,
    isLoadingTemplate,
    mutateCompletion,
    isLoadingCompletion,
    successData,
    handleShowResponse,
    handleBackToSurveys,
  } = useSurveyCompletionAndEdit({
    id,
    templateId,
    answerId,
    form,
  });

  const formDetailData = templateInfo?.data || ({} as FormAttributes);

  const handleFormSubmit = (body: {
    id: number;
    questions: QuestionSubmitData[];
    fillingTime: number;
  }) => {
    mutateCompletion(body);
  };

  return (
    <HugoThemeProvider>
      <FormFileUploadProvider>
        <FormProvider {...form}>
          <SurveyCompletionForm
            formDetailData={formDetailData}
            isLoading={isLoadingTemplate}
            isSubmitting={isLoadingCompletion}
            onSubmit={handleFormSubmit}
            successData={successData}
            onShowResponse={handleShowResponse}
            onBackToSurveys={handleBackToSurveys}
          />
        </FormProvider>
      </FormFileUploadProvider>
    </HugoThemeProvider>
  );
};

export default SurveyCompletion;
