import { Table as AntdTable, ConfigProvider, TableProps } from 'antd';
import React, { useContext, useMemo } from 'react';
import { ColumnGroupType, ColumnType } from 'antd/lib/table';
import './index.less';
import classNames from 'classnames';
import { Space } from '../Space';
import { Icon } from '../Icon';
import { translate } from '../utils';

export type ColumnsType<RecordType> = (
  | (ColumnGroupType<RecordType> & {
      actions?: (
        value: any,
        record: RecordType,
        index: number,
      ) => React.ReactNode;
    })
  | (ColumnType<RecordType> & {
      actions?: (
        value: any,
        record: RecordType,
        index: number,
      ) => React.ReactNode;
    })
)[];

interface TableExtraProps {
  columns?: ColumnsType<any>;
  emptyType?: 'simple' | 'slogan';
}

export declare type TriggerEventHandler<RecordType> = (
  record: RecordType,
  event: React.MouseEvent<HTMLElement>,
) => void;

export interface RenderExpandIconProps<RecordType> {
  prefixCls: string;
  expanded: boolean;
  record: RecordType;
  expandable: boolean;
  onExpand: TriggerEventHandler<RecordType>;
}

const Table = (props: TableExtraProps & TableProps<any>) => {
  // 为了与 antd 的生态保持兼容性，我们要求必须要使用 `.@{ant-prefix}` 变量来生成类名
  const { getPrefixCls } = useContext(ConfigProvider.ConfigContext);
  const prefixCls = getPrefixCls('btri-table');

  const { emptyType = 'simple', expandable } = props;

  const _filterIcon = (filtered: boolean) => {
    return <Icon iconName="Filter" style={{ fontSize: '16px' }}></Icon>;
  };

  const _columns: ColumnsType<any> & ColumnsType<any> = useMemo(() => {
    return props.columns?.map((column) => {
      return {
        render:
          column.actions &&
          ((value, record, index) => (
            <Space size="M">{column.actions(value, record, index)}</Space>
          )),
        filterIcon: _filterIcon,
        ...column,
      };
    });
  }, props.columns);
  const _isEmpty = useMemo(() => !props.dataSource?.length, [props.dataSource]);

  const emptyNode: React.ReactNode = useMemo(() => {
    const text = props.locale?.emptyText;
    if (typeof text === 'function') {
      return text();
    }
    return text;
  }, [props.locale?.emptyText]);

  const { locale } = useContext(ConfigProvider.ConfigContext);

  const _emptyNode = useMemo(() => {
    const nodes = {
      simple:
        emptyNode ||
        translate('packages.base.src.Table.index.暂无数据', locale?.locale),
      slogan: (
        <div>
          <img
            src={require('./icons/empty.png')}
            style={{ width: '60px', height: '60px' }}
          ></img>
          <div>
            {emptyNode ||
              translate(
                'packages.base.src.Table.index.暂无数据',
                locale?.locale,
              )}
          </div>
        </div>
      ),
    };
    return nodes[emptyType];
  }, [_isEmpty, emptyType, emptyNode]);

  const _expandIcon = (expandIconProps: RenderExpandIconProps<any>) => {
    return (
      expandIconProps.expandable && (
        <span style={{ fontSize: '16px', marginRight: '4px' }}>
          <Icon
            iconName={expandIconProps.expanded ? 'Fold' : 'Unfold'}
            onClick={(e) => expandIconProps.onExpand(expandIconProps.record, e)}
          />
        </span>
      )
    );
  };

  const _expandable = useMemo(
    () => ({ indentSize: 20, ...expandable }),
    [expandable],
  );

  return (
    <div>
      <AntdTable
        size={'middle'}
        expandIcon={_expandIcon}
        {...props}
        expandable={_expandable}
        columns={_columns}
        className={classNames(
          `${prefixCls}`,
          { [`${prefixCls}-empty`]: _isEmpty },
          props.className,
        )}
      >
        {props.children}
      </AntdTable>
      {_isEmpty && (
        <div className={classNames(`${prefixCls}-empty-icon`)}>
          {_emptyNode}
        </div>
      )}
    </div>
  );
};

Table.Summary = AntdTable.Summary;
Table.Column = AntdTable.Column;
Table.EXPAND_COLUMN = AntdTable.EXPAND_COLUMN;
Table.SELECTION_COLUMN = AntdTable.SELECTION_COLUMN;

export { Table };
