// Libs
// -----------------------------------------------------------------------------
import React, { FC, Fragment } from 'react';
import { Spin, Card, Input, Switch, Button, Space } from 'antd';
import { observer } from 'mobx-react-lite';
import { useNavigate } from 'react-router-dom';

// App
// -----------------------------------------------------------------------------
import styles from './LicenseActivationPage.module.scss';
import Layout, { LeftSidebar, makeLeftSidebarContent } from 'components/Layout';
import { paths, Page } from 'pages/AppRoutes/constants';
import { TCommonMessages, useCommonMessages } from 'components/i18n';
import { RootStore } from 'stores/RootStore';
import { useStore } from 'stores/StoreProvider';
import { useLicenseActivationPageLocale } from './i18n';
import {
  openNotificationSuccess,
  openNotificationError,
} from 'components/Messages';

export const LicenseActivationPage: FC = observer(() => {
  // Браузерная навигация
  const navigate = useNavigate();

  // Общая локализация
  const commonLocale: TCommonMessages = useCommonMessages();

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

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

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

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

  // Запустить автоматическую активацию
  const activateAuto = async (): Promise<void> => {
    if (pageStore.serial) {
      try {
        await pageStore.activateAuto(pageStore.serial);

        openNotificationSuccess({
          messageTitle: pageLocale.licenseHasBeenActivated,
        });

        await rootStore.licenseStore.fetchLicense();

        navigate(paths[Page.LICENSE_CURRENT]);
      } catch {
        openNotificationError({
          messageTitle: pageLocale.licenseActivationError,
        });
      }
    }
  };

  // Запустить ручную активацию
  const activateManual = async (): Promise<void> => {
    if (pageStore.license) {
      try {
        await pageStore.activateManual(pageStore.license);

        openNotificationSuccess({
          messageTitle: pageLocale.licenseHasBeenActivated,
        });

        await rootStore.licenseStore.fetchLicense();

        navigate(paths[Page.LICENSE_CURRENT]);
      } catch {
        openNotificationError({
          messageTitle: pageLocale.licenseActivationError,
        });
      }
    }
  };

  // Получить токен токена
  const fetchToken = async (): Promise<void> => {
    if (pageStore.serial) {
      try {
        await pageStore.fetchToken(pageStore.serial);
      } catch {
        openNotificationError({
          messageTitle: pageLocale.tokenRequestError,
        });
      }
    }
  };

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

        <div className={styles['content']}>
          <Spin spinning={pageStore.isLoading}>
            <Card
              title={pageLocale.activateNewLicense}
              className={styles['card']}
            >
              <div className={styles['field']}>
                <Space>
                  <Switch
                    id="license-manual"
                    checked={pageStore.isManual}
                    onChange={pageStore.setIsManual}
                  />

                  <label htmlFor="license-manual">
                    {pageLocale.manualActivation}
                  </label>
                </Space>
              </div>

              {pageStore.isManual ? (
                <Fragment>
                  <div className={styles['field']}>
                    <label className={styles['label']} htmlFor="license-serial">
                      {pageLocale.serial}
                    </label>

                    <Input.Group compact>
                      <Input
                        id="license-serial"
                        style={{ width: 'calc(100% - 150px)' }}
                        value={pageStore.serial}
                        onChange={(ev) => pageStore.setSerial(ev.target.value)}
                      />

                      <Button
                        style={{ width: 150 }}
                        onClick={fetchToken}
                        disabled={!pageStore.serial}
                      >
                        {pageLocale.getToken}
                      </Button>
                    </Input.Group>

                    <div className={styles['extra']}>
                      {pageLocale.placeHereProductSerialNumber}
                    </div>
                  </div>

                  <div className={styles['field']}>
                    <label className={styles['label']} htmlFor="license-token">
                      {pageLocale.token}
                    </label>

                    <Input.TextArea
                      rows={5}
                      readOnly
                      value={pageStore.token}
                      id="license-token"
                    />

                    <div className={styles['extra']}>
                      {pageLocale.sendThisTextToLicenseServer}
                    </div>
                  </div>

                  <div className={styles['field']}>
                    <label className={styles['label']} htmlFor="license-file">
                      {pageLocale.license}
                    </label>

                    <Input.Group compact>
                      <input
                        id="license-file"
                        type="file"
                        className="ant-input ant-input-file-without-button"
                        style={{ width: 'calc(100% - 150px)' }}
                        onChange={(ev) => {
                          pageStore.setLicense(ev.target?.files?.[0]);
                        }}
                      />

                      <Button
                        type="primary"
                        onClick={activateManual}
                        disabled={!pageStore.license}
                        style={{ width: 150 }}
                      >
                        {pageLocale.activate}
                      </Button>
                    </Input.Group>

                    <div className={styles['extra']}>
                      {pageLocale.selectLicenseFile}
                    </div>
                  </div>
                </Fragment>
              ) : (
                <div className={styles['field']}>
                  <label className={styles['label']} htmlFor="license-serial">
                    {pageLocale.serial}
                  </label>

                  <Input.Group compact>
                    <Input
                      id="license-serial"
                      style={{ width: 'calc(100% - 150px)' }}
                      value={pageStore.serial}
                      onChange={(ev) => pageStore.setSerial(ev.target.value)}
                    />

                    <Button
                      type="primary"
                      onClick={activateAuto}
                      style={{ width: 150 }}
                      disabled={!pageStore.serial}
                    >
                      {pageLocale.activate}
                    </Button>
                  </Input.Group>

                  <div className={styles['extra']}>
                    {pageLocale.placeHereProductSerialNumber}
                  </div>
                </div>
              )}
            </Card>
          </Spin>
        </div>
      </div>
    </Layout>
  );
});
