import { useEffect, useState } from 'react';
import { FormProvider, useForm } from 'react-hook-form';

import { type GetDrawerConfiguration } from '@material-hu/hooks/useDrawerV2';

import CreateQuestion, {
  type CreateQuestionProps,
} from 'src/pages/dashboard/Learning/Courses/New/components/TaskQuestionnaire/CreateQuestion';
import { getQuestionDrawerDefaultValues } from 'src/pages/dashboard/Learning/Courses/New/constants';
import { validateQuestion } from 'src/pages/dashboard/Learning/Courses/New/utils';
import {
  type Question,
  type QuestionFormValues,
  type Selected,
} from 'src/pages/dashboard/Learning/Courses/types';
import { QuestionType } from 'src/types/surveys';
import { useLokaliseTranslation } from 'src/utils/i18n';

export type CreateQuestionDrawerProps = CreateQuestionProps & {
  defaultValues?: Question;
  questionCount: number;
  selected: Selected;
  index: number;
  disabled?: boolean;
  onSubmitValues: (index: number, values: Question) => void;
};

export const useCreateQuestionDrawerConfig: GetDrawerConfiguration<
  CreateQuestionDrawerProps
> = args => {
  const {
    questionCount,
    defaultValues,
    selected,
    index,
    disabled,
    closeDrawer,
    onSubmitValues,
    open,
    ...createQuestionProps
  } = args;
  const { t } = useLokaliseTranslation('learning');
  const [showErrors, setShowErrors] = useState(false);

  const form = useForm<QuestionFormValues>({
    defaultValues: { type: QuestionType.TEXT },
  });

  useEffect(() => {
    const getDefaultValues = async () => {
      const values = await getQuestionDrawerDefaultValues(
        defaultValues,
        questionCount,
        t,
      );
      form.reset(values);
    };
    open && getDefaultValues();
  }, [defaultValues, open]);

  const getNewOption = (optionIndex: number) => ({
    value: t('common.option', { count: optionIndex + 1 }),
    checked: false,
  });

  const submit = (values: QuestionFormValues) => {
    const formattedValues: Question = {
      ...values,
      attachments: (values?.attachments || []).map(
        attachment => attachment.fileAsset!,
      ),
    };

    if (!validateQuestion(formattedValues)) {
      setShowErrors(true);
      return;
    }

    setShowErrors(false);
    onSubmitValues(index, formattedValues);
    handleClose();
  };

  const handleClose = () => {
    form.resetField('attachments', { defaultValue: [] });
    form.reset();
    closeDrawer();
  };

  return {
    onClose: handleClose,
    title: t('common.add_question'),
    children: (
      <FormProvider {...form}>
        <CreateQuestion
          selected={selected}
          index={index}
          showErrors={showErrors}
          getNewOption={getNewOption}
          {...createQuestionProps}
        />
      </FormProvider>
    ),
    primaryButtonProps: {
      children: t('general:save'),
      onClick: form.handleSubmit(submit),
      disabled,
      fullWidth: true,
    },
    secondaryButtonProps: {
      children: t('general:cancel'),
      onClick: handleClose,
      disabled,
      fullWidth: true,
    },
  };
};
