// Antd
import { Button, Col, Form, Row } from 'antd';

// Apps
import { DynamicTable } from 'components/DynamicTable/DynamicTable';
import { AntivirusResultTable } from '../AntivirusResultTable/AntivirusResutTable';
import { useStore } from 'stores/StoreProvider';
import { useEndpointFormConfiguration } from './useEndpointFormConfiguration';
import { observer } from 'mobx-react-lite';

// Types
import { TypeDynamicTable, TypeEndpointLargeForm } from '../types';
import { RootStore } from 'stores/RootStore';

// Styles
import styles from 'pages/DevicesDashboard/Devices.module.scss';
import { FC } from 'react';

const { Item } = Form;

export const EndpointLargeFormItems: FC<TypeEndpointLargeForm> = observer(
  ({ form, tableTranslations, locale, localeValidation }) => {
    const rootStore: RootStore = useStore();
    const devicesUiStore = rootStore.devicesUiStore;
    const endpointUiStore = rootStore.endpointUiStore;
    const antivirusResultTableUiStore = rootStore.antivirusResultTableUiStore;

    const showAntivirusScanResult = (): void => {
      if (endpointUiStore.getEndpointById?.id) {
        antivirusResultTableUiStore.fetchAntivirusEvents(
          endpointUiStore.getEndpointById?.id,
          1,
          10,
        );
      }
    };

    const {
      name,
      ip,
      port,
      integrityControlEnabled,
      integrityControlTimeout,
      prohibitCdAccess,
      rotationSettings,
      antivirusEnabled,
      description,
      whitelistAdmin,
      antivirusRemoveInfectedFiles,
      deviceControlEnabled,
      whitelistEnabled,
      antivirusStartScan,
      group,
      usbControlEnabled,
    } = useEndpointFormConfiguration(locale, localeValidation, form);

    const COLUMNS: TypeDynamicTable[] = [
      {
        title: locale.dynamicTable.pathToFile,
        dataIndex: 'path',
        width: '70%',
        editable: true,
      },

      {
        title: locale.dynamicTable.actions,
        dataIndex: 'action',
      },
    ];

    const MAIN_FORM_ITEMS_PROPS = [
      //  Имя
      name,

      // IP
      ip,

      // Порт
      port,

      // Группа
      group,

      //  Описание
      description,
    ];
    const FOLDER_SCAN_TO_START_FORM_ITEMS_PROPS = [
      //  Включить контроль целостности
      integrityControlEnabled,

      //  Период буферизации событий
      integrityControlTimeout,
    ];
    const WHITE_LIST_FORM_ITEMS_PROPS = [
      // Включить белый список
      whitelistEnabled,

      // Локальный администратор игнорирует белый список
      whitelistAdmin,
    ];

    const ANTIVIRUS_FORM_ITEMS_CONFIG = [
      //  Включить модуль антивируса
      antivirusEnabled,

      // Удалять инфицированные файлы
      antivirusRemoveInfectedFiles,
    ];

    const DEVICES_FORM_ITEMS_PROPS = [
      // Включить контроль устройств
      deviceControlEnabled,

      // Запретить доступ на чтение CD/DVD
      prohibitCdAccess,

      // Включить контроль USB устройств
      usbControlEnabled,
    ];

    const RESULTS_ANTIVIRUS_SCAN_FORM_ITEMS_PROPS = [
      // Сканирование на вирусы
      antivirusStartScan,

      {
        key: 'resultsScanningButton',
        name: 'resultsScanningButton',
        valuePropName: 'checked',
        component: (
          <Button
            disabled={devicesUiStore.isDisabledForm}
            type="primary"
            onClick={showAntivirusScanResult}
          >
            {locale.antivirusSettings.clamavResults}
          </Button>
        ),
        extra: locale.antivirusSettings.clamavResultsExtra,
      },
    ];

    const CONFIGURATION_LARGE_CARD = [
      // Основные
      {
        key: 'mainSettings',
        sectionTitle: locale.main.title,
        itemsFormFieldsArray: MAIN_FORM_ITEMS_PROPS,
      },

      // Директории сканирования при запуске
      {
        key: 'scanDirAtStartUpSettings',
        sectionTitle: locale.scanDirAtStartUp.title,
        itemsFormFieldsArray: FOLDER_SCAN_TO_START_FORM_ITEMS_PROPS,
        dynamicTableProps: {
          columns: COLUMNS,
          originData: endpointUiStore.getIntegrityControlTablePath,
          setOriginData: endpointUiStore.setIntegrityControlTablePath,
        },
      },

      // Белый список приложений
      {
        key: 'whiteListSettings',
        sectionTitle: locale.whiteList.title,
        itemsFormFieldsArray: WHITE_LIST_FORM_ITEMS_PROPS,
        dynamicTableProps: {
          columns: COLUMNS,
          originData: endpointUiStore.getWhiteListTablePathTablePath,
          setOriginData: endpointUiStore.setWhiteListTablePathTablePath,
        },
      },

      // Настройки управления устройствами
      {
        key: 'deviceManagementSettings',
        sectionTitle: locale.deviceManagementSettings.title,
        itemsFormFieldsArray: DEVICES_FORM_ITEMS_PROPS,
      },
      {
        key: 'rotationSettings',
        sectionTitle: locale.rotation.title,
        otherComponent: rotationSettings.component,
      },

      // Настройки ротации событий
      {
        key: 'antivirusSettings',
        sectionTitle: locale.antivirusSettings.title,
        itemsFormFieldsArray: ANTIVIRUS_FORM_ITEMS_CONFIG,
        dynamicTableProps: {
          columns: COLUMNS,
          originData: endpointUiStore.getAntivirusTablePath,
          setOriginData: endpointUiStore.setAntivirusTablePath,
        },
      },

      // Настройка антивируса
      {
        key: 'antivirusScanSettings',
        sectionTitle: locale.antivirusSettings.scanBlockTitle,
        itemsFormFieldsArray: RESULTS_ANTIVIRUS_SCAN_FORM_ITEMS_PROPS,
        otherComponent: (
          <AntivirusResultTable
            key="antivirusScanSettings"
            tableLocale={tableTranslations}
            antivirusLocale={locale.antivirusSettings}
          />
        ),
      },
    ];

    return (
      <>
        {CONFIGURATION_LARGE_CARD.map(
          ({
            sectionTitle,
            itemsFormFieldsArray,
            dynamicTableProps,
            key,
            otherComponent,
          }) => {
            return (
              <div key={key} style={{ marginBottom: 20 }}>
                <h4 style={{ fontWeight: '700' }}>{sectionTitle}</h4>
                <div key={1} className={styles['largeEndpointInnerCard']}>
                  {itemsFormFieldsArray && (
                    <Row gutter={[12, 12]}>
                      {itemsFormFieldsArray.map((item) => (
                        <Col key={item.key} className="gutter-row" span={8}>
                          <Item {...item}>{item.component}</Item>
                        </Col>
                      ))}
                    </Row>
                  )}
                  {dynamicTableProps && (
                    <DynamicTable
                      tableName={key}
                      disabled={devicesUiStore.isDisabledForm}
                      columns={dynamicTableProps.columns}
                      originData={dynamicTableProps.originData}
                      setOriginData={dynamicTableProps.setOriginData}
                      locales={locale.dynamicTable}
                      localeValidation={localeValidation}
                    />
                  )}
                  {otherComponent && otherComponent}
                </div>
              </div>
            );
          },
        )}
      </>
    );
  },
);
