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

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

import FormSwitcherCard from '@material-hu/components/composed-components/SwitcherCard/form';
import RadioButton from '@material-hu/components/design-system/RadioButton/RadioButton';

import { useUpdateArticleStatus } from 'src/pages/dashboard/HuLibraries/hooks/useUpdateArticleStatus';
import {
  type Article,
  ArticleNotificationType,
  ArticleStatus,
  type HeaderArticleFormValues,
  type UpdateArticleStatusPayload,
} from 'src/pages/dashboard/HuLibraries/types';
import { getHeaderArticleDefaultValues } from 'src/pages/dashboard/HuLibraries/utils';
import { handleAction } from 'src/utils/events';
import { useLokaliseTranslation } from 'src/utils/i18n';

type Props = GetDrawerConfiguration<{
  article: Article;
  title: string;
  isManagingNotifications?: boolean;
}>;

export const NotificationsSettingsDrawer: Props = ({
  closeDrawer,
  article,
  title,
  isManagingNotifications = false,
}) => {
  const { t } = useLokaliseTranslation('libraries');
  const { getValues, setValue, control, reset } =
    useFormContext<HeaderArticleFormValues>();
  const notificationType = useWatch({ control, name: 'notificationType' });

  const handleClose = () => {
    flushSync(() => reset(getHeaderArticleDefaultValues(article)));
    closeDrawer();
  };

  const updateArticleStatus = useUpdateArticleStatus({
    article,
    isManagingNotifications,
  });

  const handleNotify = () => {
    const values = getValues();

    const payload: UpdateArticleStatusPayload = {
      status: isManagingNotifications ? article.status : ArticleStatus.ENABLED,
      sendNotification: values.sendNotification,
      notificationType: values.notificationType,
    };

    updateArticleStatus.mutate(payload, { onSuccess: closeDrawer });
  };

  const options = [
    {
      value: ArticleNotificationType.PUSH,
      label: t('general:notification.push'),
    },
    {
      value: ArticleNotificationType.EMAIL,
      label: t('general:notification.email'),
    },
    {
      value: ArticleNotificationType.BOTH,
      label: t('general:notification.send_by.both'),
    },
  ];

  return {
    title,
    onClose: handleClose,
    children: (
      <Stack sx={{ gap: 3 }}>
        <Typography>{t('article.notify.description')}</Typography>
        <FormSwitcherCard
          name="sendNotification"
          switcherCardProps={{
            disabled: updateArticleStatus.isLoading,
            sx: { width: '100%' },
            slotProps: {
              switcher: {
                sx: { alignSelf: 'center', maxWidth: 'min-content' },
              },
              title: {
                fontWeight: 'fontWeightRegular',
                title: t('article.notify.activate'),
              },
            },
          }}
        >
          <Stack sx={{ mt: 2, gap: 2 }}>
            {options.map(option => (
              <RadioButton
                key={option.value}
                label={option.label}
                isActive={notificationType === option.value}
                onClick={() => setValue('notificationType', option.value)}
              />
            ))}
          </Stack>
        </FormSwitcherCard>
      </Stack>
    ),
    primaryButtonProps: {
      children: t('general:confirm'),
      fullWidth: true,
      loading: updateArticleStatus.isLoading,
      disabled: updateArticleStatus.isLoading,
      onClick: handleAction(handleNotify),
    },
    secondaryButtonProps: {
      children: t('general:cancel'),
      fullWidth: true,
      disabled: updateArticleStatus.isLoading,
      onClick: handleAction(handleClose),
    },
  };
};
