import { type MouseEvent, useEffect } from 'react';
import { FormProvider, useForm, useWatch } from 'react-hook-form';

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

import Alert from '@material-hu/components/design-system/Alert';

import useHugoUnsavedWarning from 'src/hooks/useUnsavedWarning/altHugo';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { MAX_CATEGORIES_CHILDREN } from '../../constants';
import { type CategoryItem } from '../../types';
import { hasMaxChildren } from '../../utils';
import useUpdateCategory from '../useUpdateCategory';

import { type ManageCategoryFormValues, manageCategorySchema } from './form';
import ManageCategoryForm from './ManageCategoryForm';
import {
  formatManageCategoryDefaultValues,
  formatManageCategoryParams,
} from './utils';

const useManageCategoryDrawer = (category: CategoryItem) => {
  const { t } = useLokaliseTranslation('learning');
  const defaultValues = formatManageCategoryDefaultValues(category);

  const form = useForm<ManageCategoryFormValues>({
    defaultValues,
    resolver: yupResolver(manageCategorySchema),
    mode: 'onChange',
  });

  useEffect(() => {
    reset(defaultValues);
  }, [category]);

  const { reset, handleSubmit, control } = form;
  const children = useWatch({ name: 'children', control });

  const { mutate: updateCategory, isLoading } = useUpdateCategory();

  const { modal: unsavedChanges, blocker } = useHugoUnsavedWarning({
    modalProps: {
      title: t('general:unsaved_changes.title'),
      body: t('general:unsaved_changes.description'),
      secondaryButtonProps: {
        children: t('general:unsaved_changes.exit_with_save'),
        onClick: () => {
          blocker?.reset?.();
          unsavedChanges.closeModal();
          submit();
        },
        loading: isLoading,
        disabled: isLoading,
      },
      primaryButtonProps: {
        children: t('general:unsaved_changes.confirm'),
        onClick: () => {
          blocker?.proceed?.();
          unsavedChanges.closeModal();
          close();
        },
      },
    },
    shouldBlock: form.formState.isDirty,
  });

  const submit = handleSubmit(values => {
    updateCategory(formatManageCategoryParams(category, values), {
      onSuccess: () => close(),
    });
  });

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

  const handleClose = () => {
    if (form.formState.isDirty) {
      unsavedChanges.showModal();
      return;
    }

    close();
  };

  const getDrawerConfiguration: GetDrawerConfiguration = () => {
    const handleConfirm = (event: MouseEvent<HTMLButtonElement>) => {
      event.stopPropagation();
      submit();
    };

    const handleCancel = (event: MouseEvent<HTMLButtonElement>) => {
      event.stopPropagation();
      handleClose();
    };

    return {
      title: t('categories.manage.title'),
      onClose: handleClose,
      children: (
        <FormProvider {...form}>
          {unsavedChanges.modal}
          <ManageCategoryForm
            disabled={isLoading}
            category={category}
          />
        </FormProvider>
      ),
      primaryButtonProps: {
        children: t('general:save_changes'),
        fullWidth: true,
        loading: isLoading,
        disabled: isLoading,
        onClick: handleConfirm,
      },
      secondaryButtonProps: {
        children: t('general:cancel'),
        fullWidth: true,
        disabled: isLoading,
        onClick: handleCancel,
      },
      footer: hasMaxChildren({ children }) && (
        <Alert
          severity="warning"
          title={t('categories.children.errors.max', {
            count: MAX_CATEGORIES_CHILDREN,
          })}
        />
      ),
    };
  };

  const { closeDrawer, ...result } = useDrawerV2(getDrawerConfiguration);

  return {
    closeDrawer,
    ...result,
  };
};

export default useManageCategoryDrawer;
