// Libs
// -----------------------------------------------------------------------------
import React, { FC, useEffect } from 'react';
import { Button, Card, Form, Spin } from 'antd';
import { observer } from 'mobx-react-lite';
import { ValidateErrorEntity } from 'rc-field-form/lib/interface';

// App
// -----------------------------------------------------------------------------
import styles from './ProfilePage.module.scss';
import Layout, { LeftSidebar, makeLeftSidebarContent } from 'components/Layout';
import { Page } from 'pages/AppRoutes/constants';
import { TCommonMessages, useCommonMessages } from 'components/i18n';
import { RootStore } from 'stores/RootStore';
import { useStore } from 'stores/StoreProvider';
import { useProfilePageLocale } from './i18n';
import { AccountForm } from '../AccountsDashboard/AccountForm/AccountForm';
import { TypeAccount } from 'types/default';
import {
  openNotificationError,
  openNotificationSuccess,
} from 'components/Messages';
import { handleFormRequestError } from 'components/helpers';

export const ProfilePage: FC = observer(() => {
  // Общая локализация
  const commonLocale: TCommonMessages = useCommonMessages();

  // Локализация страницы
  const pageLocale = useProfilePageLocale();

  // Содержимое боковой панели
  const leftSideBarContent = makeLeftSidebarContent(
    Page.USER_PROFILE,
    commonLocale.leftSidebar,
  );

  // Корневой стор
  const rootStore: RootStore = useStore();

  // Стор страницы
  const pageStore = rootStore.accountsStoreNew;

  // Форма
  const [form] = Form.useForm<TypeAccount>();

  // После получения текущего пользователя загрузить полную информацию о нем
  useEffect(() => {
    if (rootStore.currentUserStore.user) {
      const id = rootStore.currentUserStore.user.id;
      rootStore.accountsStoreNew.fetchOne(id);
    }
  }, [rootStore.currentUserStore.user, rootStore.accountsStoreNew]);

  // При загрузке пользователя заполнить форму его данными
  useEffect(() => {
    if (rootStore.accountsStoreNew.element) {
      form.setFieldsValue(rootStore.accountsStoreNew.element);
    }
  }, [form, rootStore.accountsStoreNew.element]);

  const onFormSubmit = async (data: TypeAccount): Promise<void> => {
    try {
      const dataId = pageStore.getId(data);
      await pageStore.update(dataId, data);
      openNotificationSuccess({
        messageTitle: pageLocale.updateSuccess,
      });
    } catch (err) {
      handleFormRequestError(
        err,
        form,
        pageLocale.updateError,
        commonLocale.notification.pleaseCheckData,
      );
    }
  };

  const onFormError = (err: ValidateErrorEntity<TypeAccount>): void => {
    if (err.errorFields.length !== 0) {
      openNotificationError({
        messageTitle: commonLocale.notification.pleaseCheckData,
      });
    }
  };

  return (
    <Layout>
      <div className={styles['page']}>
        <LeftSidebar leftSideBarContent={leftSideBarContent} />

        <div className={styles['content']}>
          <Spin spinning={pageStore.isSingleLoading}>
            <Card title={pageLocale.userProfile} className={styles['card']}>
              <AccountForm
                form={form}
                onFormSubmit={onFormSubmit}
                onFormError={onFormError}
                initialValues={pageStore.element ?? undefined}
                isNewUser={false}
                isFormDisabled={false}
                isCurrentUser={true}
                isFullSize={true}
              />
            </Card>

            <div className={styles['buttons']}>
              <div className="spacer" />
              <Button type="primary" onClick={() => form.submit()}>
                {commonLocale.confirmText.save}
              </Button>
              <Button onClick={() => form.resetFields()}>
                {commonLocale.confirmText.cancel}
              </Button>
            </div>
          </Spin>
        </div>
      </div>
    </Layout>
  );
});
