// Libs
// -----------------------------------------------------------------------------
import React, { FC, Fragment } from 'react';
import {
  Alert,
  Button,
  Descriptions,
  Form,
  List,
  Space,
  Table,
  FormInstance,
} from 'antd';
import { observer } from 'mobx-react-lite';
import { CheckOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import { Rule } from 'antd/lib/form';
import { PaginationConfig } from 'antd/es/pagination';
import { TablePaginationConfig } from 'antd';

// App
// -----------------------------------------------------------------------------
import {
  AutoCompleteMulti,
  EllipsisWithToggle,
  FormFieldsBlock,
} from 'components';
import { CORRELATION_RULE_AUTOCOMPLETE_OPTIONS } from './consts';
import { makeCorrelationRulesEventsColumns } from './makeCorrelationRulesEventsColumns';
import { useStore } from 'stores/StoreProvider';
import { CorrelationRulesRecord, EventsJournalRecord } from 'types/default';
import { CorrelationRulesCheckerHelpDialog } from './CorrelationRulesCheckerHelpDialog/CorrelationRulesCheckerHelpDialog';
import { useCorrelationRulesTemplateMessages } from '../i18n';
import { RootStore } from 'stores/RootStore';

// Props
// -----------------------------------------------------------------------------
type CorrelationRulesCheckerProps = {
  form: FormInstance<CorrelationRulesRecord>;
};

export const CorrelationRulesChecker: FC<CorrelationRulesCheckerProps> =
  observer(({ form }) => {
    const rootStore: RootStore = useStore();
    const store = rootStore.correlationRulesCheckerUiStore;
    const pageStore = rootStore.correlationRulesUiStore;

    const locale = useCorrelationRulesTemplateMessages();
    const blockStrings = locale.conditionRuleMessage;
    const fieldRules: Array<Rule> = [
      { required: true, message: locale.formValidationMessages.emptyField },
    ];

    const getQuery = (): string =>
      form.getFieldValue(['rule_json', 'operands']);

    const commonPaginationConfig: TablePaginationConfig & PaginationConfig = {
      pageSize: store.foundEventsTablePageSize,
      current: store.foundEventsTablePage,
      total: store.foundEventsCount,
      showTotal: (total: number) => `${blockStrings.event.total}: ${total}`,
      showSizeChanger: true,
      size: 'default',
      onChange: (page: number, pageSize: number) => {
        const query = getQuery();
        store.onFoundEventsTablePagination(page, pageSize, query);
      },
      locale: {
        items_per_page: '',
      },
    };

    const commonHeader = (
      <div style={{ fontSize: 16, fontWeight: 600 }}>
        {blockStrings.event.foundEvents} ({store.foundEventsCount})
      </div>
    );

    return (
      <FormFieldsBlock
        title={
          <Fragment>
            {blockStrings.headerTitle}{' '}
            <QuestionCircleOutlined
              color={'royalblue'}
              onClick={() => store.setHelpDialogIsVisible(true)}
            />
          </Fragment>
        }
        headerExtra={
          <Button
            icon={<CheckOutlined />}
            loading={store.isRuleCheckLoading}
            onClick={() => store.checkRule(getQuery())}
            disabled={pageStore.isFormDisabled || store.isRuleCheckLoading}
          >
            {blockStrings.checkButton}
          </Button>
        }
      >
        <Space
          direction="vertical"
          style={{ display: 'flex' }}
          size={pageStore.cardSize === 'large' ? 'middle' : 'small'}
        >
          <Form.Item
            label={blockStrings.title}
            rules={fieldRules}
            name={['rule_json', 'operands']}
          >
            <AutoCompleteMulti
              disabled={pageStore.isFormDisabled || store.isRuleCheckLoading}
              options={CORRELATION_RULE_AUTOCOMPLETE_OPTIONS}
              onKeyDown={store.onRuleInput}
            />
          </Form.Item>

          {store.isRuleChecked && (
            <Fragment>
              {store.isRuleModified && (
                <Alert
                  type="info"
                  showIcon
                  message={blockStrings.event.ruleHasBeenModified}
                />
              )}

              {pageStore.cardSize === 'large' ? (
                <Table
                  title={() => commonHeader}
                  columns={makeCorrelationRulesEventsColumns(blockStrings)}
                  dataSource={store.foundEvents}
                  size={pageStore.cardSize === 'large' ? 'middle' : 'small'}
                  style={{ width: '100%' }}
                  pagination={{
                    ...commonPaginationConfig,
                    size: 'default',
                  }}
                  locale={{ emptyText: blockStrings.event.noEventsFound }}
                  loading={store.isRuleCheckLoading}
                />
              ) : (
                <List
                  header={commonHeader}
                  size="small"
                  dataSource={store.foundEvents}
                  pagination={{
                    ...commonPaginationConfig,
                    size: 'small',
                  }}
                  locale={{
                    emptyText: blockStrings.event.noEventsFound,
                  }}
                  loading={store.isRuleCheckLoading}
                  renderItem={(event: EventsJournalRecord) => (
                    <List.Item>
                      <Descriptions
                        labelStyle={{ fontWeight: '600' }}
                        column={2}
                        size="small"
                      >
                        <Descriptions.Item
                          label={blockStrings.event.created}
                          span={2}
                        >
                          {event._source['@created']}
                        </Descriptions.Item>

                        <Descriptions.Item
                          label={blockStrings.event.id}
                          span={2}
                        >
                          {event._source.event_id}
                        </Descriptions.Item>

                        <Descriptions.Item label={blockStrings.event.severity}>
                          {event._source.event_severity}
                        </Descriptions.Item>

                        <Descriptions.Item label={blockStrings.event.category}>
                          {event._source.sign_category}
                        </Descriptions.Item>

                        <Descriptions.Item
                          label={blockStrings.event.message}
                          span={2}
                        >
                          <EllipsisWithToggle
                            text={event._source.event_src_msg}
                            collapseLabel={blockStrings.event.showLess}
                            expandLabel={blockStrings.event.showMore}
                            maxWidth={300}
                          />
                        </Descriptions.Item>

                        <Descriptions.Item
                          label={blockStrings.event.combinedIp}
                          span={2}
                        >
                          {event._source.source_ip} /{' '}
                          {event._source.destination_ip}
                        </Descriptions.Item>
                      </Descriptions>
                    </List.Item>
                  )}
                />
              )}
            </Fragment>
          )}
        </Space>

        <CorrelationRulesCheckerHelpDialog
          isVisible={store.helpDialogIsVisible}
          onClose={() => {
            store.setHelpDialogIsVisible(false);
          }}
        />
      </FormFieldsBlock>
    );
  });
