// Hooks
import { useEffect } from 'react';
import { useStore } from 'stores/StoreProvider';

// Types
import { RootStore } from 'stores/RootStore';
import { TypeCardInfoSensorMessages } from 'pages/DevicesDashboard/types';
import { FormInstance } from 'antd/lib/form';
import { TypeSensorConfiguration } from '../types';
import { TypeCommonValidationMessages } from 'components/i18n';

// Antd
import { Button, Checkbox, Form, Input, InputNumber, Select } from 'antd';
import { CopyOutlined } from '@ant-design/icons';

// Components
import { validationIp } from 'pages/AssetsDashboard/AssetsCardInfo/validation';
import { openNotificationSuccess } from 'components/Messages';

// Antd Items
const { TextArea } = Input;

export const useSensorFormConfiguration = (
  locale: TypeCardInfoSensorMessages,
  localeValidation: TypeCommonValidationMessages,
  form: FormInstance,
): TypeSensorConfiguration => {
  // Stores
  const rootStore: RootStore = useStore();
  const devicesUiStore = rootStore.devicesUiStore;
  const sensorStore = rootStore.sensorStore;

  const eventInterface = sensorStore.getSensorInterfacesById?.data?.map(
    (item) => item,
  );

  useEffect(() => {
    form.getFieldsValue();
  }, [form]);

  const isAuthorizationKey = form.getFieldValue('authorization_key');

  // Функция для копирования значения поля authorization_key
  const copyAuthorizationKey = async (): Promise<void> => {
    // Берем значение поля authorization_key из формы

    if (isAuthorizationKey) {
      // Записываем значание в буфер
      await navigator.clipboard.writeText(isAuthorizationKey);
      openNotificationSuccess({
        messageTitle: locale.notification.copyAuthorizationKeySuccess,
      });
    }
  };

  const formItemLayout = {
    labelCol: { span: 7 },
    wrapperCol: { span: 24 },
  };

  return {
    // Имя
    name: (
      <Form.Item
        key="name"
        name="name"
        label={locale.main.name.title}
        extra={locale.main.name.extra}
        rules={[
          {
            required: true,
            message: localeValidation.fieldNotBeEmpty,
          },
          {
            max: 128,
            message: localeValidation.nameMaxLength,
          },
        ]}
      >
        <Input
          disabled={devicesUiStore.isDisabledForm}
          placeholder={locale.main.name.placeholder}
        />
      </Form.Item>
    ),

    // Ip
    ip: (
      <Form.Item
        key="ip"
        name="ip"
        label={locale.main.ip.extra}
        extra={locale.main.ip.extra}
        rules={[
          {
            required: true,
            message: localeValidation.fieldNotBeEmpty,
          },
          () => ({
            async validator(_: unknown, value: string) {
              await validationIp(_, value, localeValidation.ipValidation);
            },
          }),
        ]}
      >
        <Input
          disabled={devicesUiStore.isDisabledForm}
          placeholder={locale.main.ip.placeholder}
        />
      </Form.Item>
    ),

    // Порт
    port: (
      <Form.Item
        key="port"
        name="port"
        label={locale.main.port.title}
        extra={locale.main.port.extra}
        rules={[
          {
            required: true,
            message: localeValidation.fieldNotBeEmpty,
          },
        ]}
      >
        <InputNumber
          style={{ width: '100%' }}
          min={1500}
          max={65535}
          disabled={devicesUiStore.isDisabledForm}
          placeholder={locale.main.port.placeholder}
        />
      </Form.Item>
    ),

    // Группа
    group: (
      <Form.Item
        key="group"
        name="group"
        label={locale.main.group.title}
        extra={locale.main.group.extra}
      >
        <Select
          allowClear
          disabled={devicesUiStore.isDisabledForm}
          options={devicesUiStore.groupList.map((item) => ({
            value: item.id,
            label: item.name,
          }))}
        />
      </Form.Item>
    ),

    // Доп. инфо ( Описание )
    description: (
      <Form.Item
        key="description"
        name="description"
        label={locale.main.description}
      >
        <TextArea
          style={{ height: 30 }}
          disabled={devicesUiStore.isDisabledForm}
        />
      </Form.Item>
    ),

    // Строка авторизации
    authorizationKey: (
      <Form.Item
        name="authorization_key"
        label={locale.main.authenticationKey.title}
        help={
          !isAuthorizationKey
            ? locale.main.authenticationKey.help.emptyField
            : locale.main.authenticationKey.help.fullField
        }
      >
        <Input
          disabled
          addonAfter={
            <Button
              disabled={!isAuthorizationKey}
              type="link"
              icon={<CopyOutlined />}
              onClick={copyAuthorizationKey}
              style={{ padding: 0, height: 0 }}
            />
          }
        />
      </Form.Item>
    ),

    // Span
    // Имя
    spanInterfaceName: (
      <Form.Item
        key="span_interface_name"
        name="span_interface"
        label={locale.interfaceFields.name}
        extra={locale.interfaceFields.extra}
        {...formItemLayout}
      >
        <Select
          disabled={devicesUiStore.isDisabledForm}
          options={eventInterface?.map((item) => ({
            value: item.interface,
            label: item.interface,
          }))}
        />
      </Form.Item>
    ),

    // Включить сигнатурный анализ
    signatureAnalysis: (
      <Form.Item
        key="signature_analysis"
        name="signature_analysis"
        valuePropName="checked"
      >
        <Checkbox disabled={devicesUiStore.isDisabledForm}>
          {locale.networkTrafficAnalyzers.enableSignatureAnalysis}
        </Checkbox>
      </Form.Item>
    ),

    // Включить анализ протоколов DPI
    protocolsAnalysis: (
      <Form.Item
        key="protocols_analysis"
        name="protocols_analysis"
        valuePropName="checked"
      >
        <Checkbox disabled={devicesUiStore.isDisabledForm}>
          {locale.networkTrafficAnalyzers.enableDpiProtocolAnalysis}
        </Checkbox>
      </Form.Item>
    ),
  };
};
