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

import Typography from '@material-hu/mui/Typography';

import Button from '@material-hu/components/design-system/Buttons/Button';
import useHuSnackbar from '@material-hu/components/design-system/Snackbar';

import { KnowledgeLibraryArticle } from 'src/types/library';
import { useLokaliseTranslation } from 'src/utils/i18n';

import BasicDrawer from 'src/components/BasicDrawer';

import useUpdateLibraryNotify, {
  Values,
} from '../hooks/useUpdateLibraryNotify';

import NotificationsSettingsForm from './NotificationsSettingsForm';

export type NotificationsSettingsDrawerProps = {
  onClose: () => void;
  onCancel?: () => void;
  onSubmit?: () => void;
  library: KnowledgeLibraryArticle;
};

export const NotificationsSettingsDrawer = ({
  library,
  onClose,
  onCancel = () => null,
  onSubmit = () => null,
}: NotificationsSettingsDrawerProps) => {
  const { t } = useLokaliseTranslation('libraries');
  const { enqueueSnackbar } = useHuSnackbar();

  const form = useForm({
    defaultValues: {
      notify: library.notify,
      notificationType: library.notificationType,
    },
  });

  const { handleSubmit, reset, formState } = form;

  const notifyMutation = useUpdateLibraryNotify(library);

  const submit = (values: Values) => {
    onSubmit();
    notifyMutation.mutate(values, {
      onSuccess: () => {
        onClose();
        enqueueSnackbar({
          title: t('general:notification.updated'),
          variant: 'success',
        });
        reset();
      },
    });
  };

  const handleCancel = () => {
    onClose();
    onCancel();
    reset();
  };

  return (
    <FormProvider {...form}>
      <BasicDrawer.Container
        component="form"
        onSubmit={event => event.preventDefault()}
        sx={{ gap: 2 }}
      >
        <Typography
          variant="globalM"
          fontWeight="fontWeightRegular"
        >
          {t('article.notify.description')}
        </Typography>
        <NotificationsSettingsForm />
        <BasicDrawer.Actions sx={{ p: 0 }}>
          <Button
            id="notifications-settings-cancel-button"
            variant="text"
            onClick={handleCancel}
            fullWidth
          >
            {t('general:cancel')}
          </Button>
          <Button
            id="notifications-settings-accept-button"
            onClick={handleSubmit(submit)}
            variant="contained"
            disabled={!formState.isDirty}
            loading={notifyMutation.isLoading}
            fullWidth
          >
            {t('general:save')}
          </Button>
        </BasicDrawer.Actions>
      </BasicDrawer.Container>
    </FormProvider>
  );
};

export default NotificationsSettingsDrawer;
