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

import { yupResolver } from '@hookform/resolvers/yup';
import { type GetDrawerConfiguration } from '@material-hu/hooks/useDrawerV2';

import { queryClient } from 'src/config/react-query';
import { useLokaliseTranslation } from 'src/utils/i18n';

import useCreateCategory from '../../../hooks/useCreateCategory';
import { categoriesKeys } from '../../../queries';
import { type CreateCategoryParams } from '../../../types';

import CreateCategoryForm from './CreateCategoryForm';
import { type CreateCategoryFormValues, createCategorySchema } from './form';

export const CreateCategoryDrawer: GetDrawerConfiguration = args => {
  const { closeDrawer } = args;
  const { t } = useLokaliseTranslation('learning');

  const form = useForm<CreateCategoryFormValues>({
    defaultValues: {
      categoryType: 'principal',
      categoryName: '',
      parentCategory: null,
    },
    resolver: yupResolver(createCategorySchema),
    mode: 'onChange',
  });

  const { reset, handleSubmit } = form;

  const { mutate: createCategory, isLoading: isCreatingCategory } =
    useCreateCategory();

  const onSubmitForm = handleSubmit(data => {
    const payload: CreateCategoryParams = {
      name: data.categoryName,
      parentId: data.parentCategory?.value,
    };

    createCategory(payload, {
      onSuccess: () => {
        queryClient.invalidateQueries(categoriesKeys.list.all());
        handleCloseDrawer();
      },
    });
  });

  const handleCloseDrawer = () => {
    reset();
    closeDrawer();
  };

  return {
    title: t('categories.create'),
    onClose: handleCloseDrawer,
    children: (
      <FormProvider {...form}>
        <CreateCategoryForm isLoading={isCreatingCategory} />
      </FormProvider>
    ),
    primaryButtonProps: {
      children: t('general:create'),
      fullWidth: true,
      loading: isCreatingCategory,
      disabled: isCreatingCategory,
      onClick: e => {
        e.stopPropagation();
        onSubmitForm();
      },
    },
    secondaryButtonProps: {
      children: t('general:cancel'),
      fullWidth: true,
      disabled: isCreatingCategory,
      onClick: e => {
        e.stopPropagation();
        handleCloseDrawer();
      },
    },
  };
};
