import { useCallback, useEffect, useState } from 'react';
import { observer } from 'mobx-react-lite';
import { onSelectAllRow, onSelectOnceRow, usePathName } from './helpers';
import { useParams } from 'react-router-dom';
import { useStore } from 'stores/StoreProvider';
import { sorterColumnTable } from '../helpers';
import { Button, Checkbox, Pagination, Select, Table, TableProps } from 'antd';
import { TableRowSelection } from 'antd/lib/table/interface';
import { Page, paths } from 'pages/AppRoutes/constants';
import { TCommonMessages, useCommonMessages } from '../i18n';
import i18next from 'i18next';
import classNames from 'classnames';
import styles from './DashboardTable.module.scss';

const { Option } = Select;

const DashboardTable = observer((props: any): JSX.Element => {
  const {
    actionsWithSelectedCards,
    actionsWithCards,
    columns,
    onRowEvent,
    cards,
    pageState,
    loading,
    setSelectedTag,
    rowSelection,
    addNewEntity,
    changeRowCount,
    cardInfoComponent,
    setSorterField,
    setCheckedColumns,
    getCheckedColumns,
    setDisabledForm,
    getRowId = (record: any) => record.id,
    getCheckboxProps,
  } = props;

  if (!cards) {
    return <div>Страница временно не доступна</div>;
  }

  const path = usePathName();

  const hasSelected = rowSelection?.selectedRowKeys?.length > 0;

  const [isOpened, setIsOpened] = useState<boolean | undefined>();
  const { id: idx } = useParams();
  const translations: TCommonMessages = useCommonMessages();

  const { collapse } = useStore().helpersStore;

  //  Todo Запись столбцов в стору </
  useEffect(() => {
    setCheckedColumns(columns);
  }, [path]);
  // Todo />

  useEffect(() => {
    if (getCheckedColumns.length !== 0) {
      setCheckedColumns(
        columns.map((item: any, index: number) => {
          return {
            ...item,
            hidden: getCheckedColumns[index]?.hidden,
            sorter: getCheckedColumns[index]?.sorter,
            sortOrder: getCheckedColumns[index]?.sortOrder,
          };
        }),
      );
    }
  }, [i18next.language]);

  const isRowActions =
    path === paths[Page.ACCOUNTS_USER] ||
    path === paths[Page.ASSETS_DASHBOARD] ||
    path ===
      `${paths[Page.ASSETS_DASHBOARD]}/${idx === 'groups' ? null : idx}` ||
    path === paths[Page.INCIDENTS_DASHBOARD] ||
    path === `${paths[Page.INCIDENTS_DASHBOARD]}/${idx}` ||
    path === paths[Page.EVENTS_JOURNAL] ||
    path === paths[Page.DEVICES_DASHBOARD] ||
    path === `${paths[Page.DEVICES_DASHBOARD]}/${idx}` ||
    path === paths[Page.SECURITY_SYSTEM_GROUP] ||
    path === paths[Page.STORAGE] ||
    path === `${paths[Page.STORAGE]}/${idx}` ||
    path === paths[Page.CORRELATION_RULES_DASHBOARD] ||
    path === paths[Page.CORRELATION_RULES_GROUPS_DASHBOARD] ||
    path ===
      `${paths[Page.CORRELATION_RULES_DASHBOARD]}/${
        idx === 'groups' ? null : idx
      }`;

  const isTagTable =
    path === '/assets/groups' || path === '/correlation_rules/groups';

  const rowItemSelection: TableRowSelection<any> = {
    // selectedRowKeys - массив выбранных строк в таблице по id
    selectedRowKeys: rowSelection?.selectedRowKeys,

    //функция возвращающая набор данных при разовом выборе одного элемента
    onSelect: (record: any, selected: boolean, selectedRows: any[]) =>
      onSelectOnceRow(
        selected,
        selectedRows,
        record,
        rowSelection.onSetSelectedRowItem,
        getRowId,
      ),

    //функция возвращающая набор данных при разовом выборе всех элементов
    onSelectAll: (selected: boolean, selectedRows: any[], changeRows: any[]) =>
      onSelectAllRow(
        selected,
        selectedRows,
        changeRows,
        rowSelection,
        getRowId,
      ),

    // Задать дополнительные настройки чекбокса выделения строки
    getCheckboxProps,
  };

  const visibleOn = (): void => {
    setIsOpened(true);
  };
  const visibleOff = (): void => {
    setIsOpened(false);
  };

  const checkedColumnItem = useCallback((e, col, checkedcol) => {
    const checked = e.target.checked;
    const id = e.target.id;
    const index = col.findIndex((item: any) => item.key === id);

    if (!checked) {
      checkedcol[index].hidden = true;

      setCheckedColumns(checkedcol);
    } else {
      checkedcol[index].hidden = false;
      setCheckedColumns(checkedcol);
    }
  }, []);

  const handleTableChange = (current: number, pageSize: number): void =>
    changeRowCount(current, pageSize);

  const handleSorterTableChange: TableProps<typeof cards>['onChange'] =
    useCallback(
      (_, __, sorter): void => {
        sorterColumnTable(
          { field: sorter.field, order: sorter.order },
          setSorterField,
        );
      },
      [setSorterField],
    );

  return (
    <div
      className={classNames(styles['container'], {
        [styles['container-collapsed']]: collapse,
        [styles['container-not-collapsed']]: !collapse,
      })}
    >
      <div className={styles['container_actions_button']}>
        <div className={styles['container_column-dropdown']}>
          <Select
            style={{ width: 210 }}
            bordered={false}
            value={translations.columnsSelector}
            open={isOpened}
            onFocus={visibleOn}
            onBlur={visibleOff}
          >
            {getCheckedColumns?.map((item: any) => {
              return (
                <Option key={item.key} value={item.key}>
                  <div
                    style={{
                      width: '100%',
                      display: 'flex',
                      justifyContent: 'space-between',
                    }}
                  >
                    <span>{item.title}</span>
                    <Checkbox
                      disabled={
                        item.disabled ||
                        item.dataIndex === 'name' ||
                        item.dataIndex === 'title'
                      }
                      checked={!item.hidden}
                      id={item.key}
                      onChange={(e) =>
                        checkedColumnItem(e, columns, getCheckedColumns)
                      }
                    />
                  </div>
                </Option>
              );
            })}
          </Select>
          {actionsWithCards}
          {hasSelected && actionsWithSelectedCards}
          <span style={{ marginLeft: 8 }}>
            {hasSelected
              ? translations.table.selectedItemsCount(
                  rowSelection.selectedRowKeys.length,
                )
              : ''}
          </span>
        </div>
        {!isTagTable && addNewEntity && addNewEntity.entity}
        {/*Todo В будущем удалить, группы будут приходить со страниц*/}
        {isTagTable && (
          <Button
            className={styles['download_button']}
            onClick={() => {
              setSelectedTag(undefined);
              setDisabledForm(false);
            }}
            type="primary"
          >
            {translations.button.addGroup}
          </Button>
        )}
      </div>
      {getCheckedColumns && (
        <>
          <Table
            className={classNames(styles['customTable_data'], {
              [styles['customTable_no-data']]: !cards.length,
            })}
            size="small"
            rowSelection={rowSelection && rowItemSelection}
            columns={getCheckedColumns.filter((item: any) => !item.hidden)}
            dataSource={cards}
            loading={loading}
            pagination={false}
            rowKey={getRowId}
            tableLayout="fixed"
            scroll={{ x: 600, y: 600 }}
            onRow={(record) => {
              return {
                onClick: () => {
                  if (isRowActions) {
                    onRowEvent(record);
                  }
                },
              };
            }}
            onChange={handleSorterTableChange}
          />
          <Pagination
            className={styles['pagination']}
            showSizeChanger
            size="default"
            onChange={handleTableChange}
            {...pageState}
          />
        </>
      )}
      {cardInfoComponent}
    </div>
  );
});

export default DashboardTable;
