// Antd
import {
  CopyOutlined,
  RedoOutlined,
  RetweetOutlined,
  SmallDashOutlined,
} from '@ant-design/icons';
import { Tag } from 'antd';

// Types
import { TypeButton } from 'components/DashboardTable/components/SingleActionsCard/types';
import { ColumnsType } from 'antd/es/table';
import { TypeSingleActionMessages } from './types';
import {
  ArmaIndustrialFirewall,
  DeviceType,
  EndpointDevice,
  SensorDevice,
} from 'myApi';
import { TypeConfirmMessages } from 'components/i18n';

// Components
import StatusType from 'components/DashboardTable/components/StatusType/StatusType';
import SingleActionsCard from 'components/DashboardTable/components/SingleActionsCard/SingleActionsCard';
import { showConfirmModal } from 'components/Modals/ConfirmModal/ConfirmModal';

// Apps
import moment from 'moment';

// Styles
import styles from '../AssetsDashboard/helpers.module.scss';

export const makeDevicesColumns = (
  translations: {
    columnMessages: { [key: string]: string };
    singleActionMessages: TypeSingleActionMessages;
    commonMessages: TypeConfirmMessages;
  },
  handleActions: {
    onDelete: (id: number[]) => void;
    onEdit: (type: DeviceType, id: number) => void;
    onDownload: (type: string, id: number) => void;
    onUpload: (type: 'config' | 'rules', id: number, files?: FormData) => void;
    onUpdate: (ids: number[]) => void;
    onCopyEndpoint: (id: number) => void;
    onRebootFirewall: (id: number) => void;
  },
): ColumnsType<ArmaIndustrialFirewall | EndpointDevice | SensorDevice> => {
  const { id, status, name, type, ip, groups, info, update, actions, port } =
    translations.columnMessages;

  const {
    downloadFireWallConfig,
    uploadFireWallConfig,
    uploadFireWallRules,
    downloadEndpointConfig,
    updateEndpointConfig,
    firewallReboot,
    deleting,
  } = translations.singleActionMessages;

  const { edit, ok, cancel } = translations.commonMessages;

  const {
    onDelete,
    onEdit,
    onDownload,
    onUpload,
    onUpdate,
    onCopyEndpoint,
    onRebootFirewall,
  } = handleActions;

  return [
    {
      title: id,
      dataIndex: 'id',
      key: 'id',
      width: '10%',
      align: 'center',
      sorter: true,
    },
    {
      title: status,
      dataIndex: 'status',
      key: 'status',
      width: '10%',
      align: 'center',
      // Пока запретим сортировать, как на бэке починят - вернем
      // sorter: true,
      render: (_, { status: statusType }) => {
        const validStatusType = statusType?.status || 'connecting';
        return <StatusType statusType={validStatusType} />;
      },
    },
    {
      title: name,
      dataIndex: 'name',
      key: 'name',
      width: '15%',
      align: 'center',
      sorter: true,
    },
    {
      title: type,
      dataIndex: 'type',
      key: 'type',
      width: '15%',
      align: 'center',
      sorter: true,
      render: (text) => {
        if (text) {
          return text[0].toUpperCase() + text.substring(1);
        }
      },
    },
    {
      title: ip,
      dataIndex: 'ip',
      key: 'ip',
      width: '10%',
      align: 'center',
      sorter: true,
    },
    {
      title: groups,
      dataIndex: 'group',
      key: 'group',
      width: '10%',
      align: 'center',
      sorter: true,
      render: (_, { group }) =>
        group?.name ? (
          <Tag className={styles['tags']} color="blue">
            {group.name}
          </Tag>
        ) : (
          <SmallDashOutlined />
        ),
    },
    {
      title: port,
      dataIndex: 'port',
      key: 'port',
      width: '15%',
      align: 'center',
      sorter: true,
    },
    {
      title: info,
      dataIndex: 'description',
      key: 'description',
      width: '15%',
      align: 'center',
      sorter: true,
    },
    {
      title: update,
      dataIndex: 'updated',
      key: 'updated',
      width: '15%',
      align: 'center',
      sorter: true,
      render: (_, { updated }) => {
        return (
          <div>
            {updated ? moment(updated).format('DD.MM.YY HH:mm:ss') : null}
          </div>
        );
      },
    },

    {
      title: actions,
      dataIndex: 'action',
      key: 'action',
      width: '15%',
      align: 'center',
      render: (_, { id: rowId, type: rowType, status: deviceStatus }) => {
        const isFirewallActionButtonDisabled =
          rowType === DeviceType.Firewall && deviceStatus?.status !== 'online';

        const customConfig: {
          endpoint: TypeButton[];
          firewall: TypeButton[];
        } = {
          endpoint: [
            {
              key: 'update',
              type: 'customButton',
              translation: updateEndpointConfig,
              action: () => onUpdate([rowId as number]),
            },
            {
              key: 'download',
              type: 'customButton',
              translation: downloadEndpointConfig,
              action: () => onDownload(rowType as string, rowId as number),
            },
            {
              key: 'copyElement',
              type: 'customButton',
              translation: 'Копировать конфигурацию Endpoint',
              action: () => onCopyEndpoint(rowId as number),
              icon: CopyOutlined,
            },
          ],
          firewall: [
            {
              fileName: 'conffile',
              key: 'conffile',
              type: 'upload',
              translation: uploadFireWallConfig,
              action: (files?: FormData) =>
                onUpload('config', rowId as number, files),
              disabled: isFirewallActionButtonDisabled,
            },
            {
              key: 'downloadIFConfiguration',
              type: 'download',
              translation: downloadFireWallConfig,
              action: () => onDownload(rowType as string, rowId as number),
              disabled: isFirewallActionButtonDisabled,
            },
            {
              fileName: 'rulesets',
              key: 'rulesets',
              type: 'upload',
              translation: uploadFireWallRules,
              action: (files?: FormData) =>
                onUpload('rules', rowId as number, files),
              icon: RedoOutlined,
              disabled: isFirewallActionButtonDisabled,
            },
            {
              key: 'reboot',
              type: 'customButton',
              translation: firewallReboot,
              action: () => onRebootFirewall(rowId as number),
              icon: RetweetOutlined,
              disabled: isFirewallActionButtonDisabled,
            },
          ],
        };

        return (
          <SingleActionsCard
            buttonsConfig={[
              {
                key: 'edit',
                type: 'customButton',
                translation: edit,
                action: () => onEdit(rowType as DeviceType, rowId as number),
              },
              {
                key: 'delete',
                type: 'customButton',
                translation: deleting.popover,
                action: () => {
                  showConfirmModal({
                    title: deleting.confirm,
                    okType: 'danger',
                    action: () => onDelete([rowId as number]),
                    okText: ok,
                    cancelText: cancel,
                  });
                },
              },
              customConfig[rowType as 'endpoint' | 'firewall'],
            ]}
          />
        );
      },
    },
  ];
};
