import { observer } from 'mobx-react-lite';
import { TypeTags, TypeTagCreate } from 'types/default';
import { ValidateErrorEntity } from 'rc-field-form/lib/interface';
import { TCommonMessages } from 'components/i18n';
import { openNotificationWithIcon } from 'components/Notification';
import TagFormTemplate from './TagFormTemplate';

type TGetSelectedTagId = number | undefined | null;

type Props = {
  getSelectedTagId: TGetSelectedTagId;
  getSelectedTag: TypeTagCreate | TypeTags | undefined;
  setSelectedTag: (val: null) => void;
  postGroupsList: (values: TypeTags) => void;
  patchGroupsList: (values: TypeTags, id: number) => void;
  disabled: boolean;
  setDisabled: (values: boolean) => void;
  title: string;
  translations: TCommonMessages;
};

export const TagDrawer = observer(
  ({
    title,
    getSelectedTagId,
    getSelectedTag,
    setSelectedTag,
    postGroupsList,
    patchGroupsList,
    setDisabled,
    disabled,
    translations,
  }: Props): JSX.Element => {
    const onClose = (): void => {
      setSelectedTag(null);
      setDisabled(true);
    };

    const onFinish = (values: TypeTags): void => {
      if (!getSelectedTagId) {
        postGroupsList(values);
      } else {
        patchGroupsList(values, getSelectedTagId);
      }
    };

    const onFinishFailed = (e: ValidateErrorEntity): void => {
      if (e.errorFields.length !== 0)
        openNotificationWithIcon('error', {
          message: translations.notification.pleaseCheckData,
        });
    };

    return (
      <TagFormTemplate
        translations={translations}
        title={title}
        getSelectedTag={getSelectedTag}
        onClose={onClose}
        onFinish={onFinish}
        setDisabled={setDisabled}
        disabled={disabled}
        onFinishFailed={onFinishFailed}
      />
    );
  },
);
