import { useFormContext, useWatch } from 'react-hook-form';

import { useDrawerV2 } from '@material-hu/hooks/useDrawerV2';
import { IconBellRinging } from '@material-hu/icons/tabler';

import { type ArticleFormValues } from 'src/pages/dashboard/HuLibraries/schemas';
import { type NotificationsValues } from 'src/pages/dashboard/HuLibraries/types';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { NotificationsSettingsDrawer } from '../components/NotificationsSettingsDrawer';

export const useNotificationsActions = () => {
  const { t } = useLokaliseTranslation('general');
  const { setValue, control } = useFormContext<ArticleFormValues>();

  const [sendNotification, notificationType] = useWatch({
    control,
    name: ['sendNotification', 'notificationType'],
  });

  const { drawer: notificationsDrawer, showDrawer: showNotificationsDrawer } =
    useDrawerV2(NotificationsSettingsDrawer);

  const handleManageNotifications = () => {
    showNotificationsDrawer({
      defaultValues: { sendNotification, notificationType },
      onConfirm: (values: NotificationsValues) => {
        const notifyChanged = values.sendNotification !== sendNotification;
        const typeChanged = values.notificationType !== notificationType;

        if (notifyChanged) {
          setValue('sendNotification', values.sendNotification, {
            shouldDirty: true,
          });
        }
        if (typeChanged) {
          setValue('notificationType', values.notificationType, {
            shouldDirty: true,
          });
        }
      },
    });
  };

  const actions = [
    {
      when: true,
      action: {
        key: 'manage-notifications',
        title: t('notification.manage'),
        onClick: handleManageNotifications,
        avatar: { Icon: IconBellRinging },
      },
    },
  ];

  return {
    actions,
    components: notificationsDrawer,
  };
};
