import React, { useMemo, useState } from 'react';
import classNames from 'classnames';
import Skeleton from 'antd/es/skeleton';
import 'antd/es/skeleton/style/index';
import Row from 'antd/es/row';
import Col from 'antd/es/col';
import 'antd/es/grid/style/index';
import Tooltip from 'antd/es/tooltip';
import 'antd/es/tooltip/style/index';
import Collapse from 'antd/es/collapse';
import 'antd/es/collapse/style/index';
import { tableScroll, inspectEllipsisQuick } from '@jy-fe/utils/es/joyowoUmi';
import XuiListPage from '../xui-list-page';
import { XuiDetailInformationProps } from './xui-detail-information.d';

const XuiDetailInformation: React.FC<XuiDetailInformationProps> = ({
  title,
  buttonGroup,
  extra,
  type = 'info',
  info,
  grid = 3,
  rowKey = 'id',
  columns = [],
  dataSource = [],
  paginationConfig,
  list,
  border,
  footerInfo,
  loading,
  listCollapseData,
}) => {
  const className = 'xui-ant__detail-information';

  const [visible, setVisible] = useState(false);
  const [overClassName, setOverClassName] = useState('');

  /** info模式下 组装基本信息/图片信息展示 */
  const getColItems = () => {
    if (!info) {
      return [];
    }
    if (type === 'info') {
      return info.map((data, index) => {
        if (data.type === 'pictures') {
          return (
            <Col key={data.label} span={24 / grid} className={`${className}--body--col`}>
              <span className={`${className}--body--col--label`}>{data.label}</span>
              {(data.content as string[]).map(item => (
                <img
                  key={`${item}-${index.toString()}`}
                  src={item}
                  alt={item}
                  className={`${className}--body--info--pic`}
                  onClick={() => window.open(item)}
                />
              ))}
            </Col>
          );
        }

        const currentParentClassNameNoEllipsis = `${className}--body--col_no-ellipsis`;
        const currentClassNameNoEllipsis = `${className}--body--col--content_no-ellipsis`;

        if (data.noEllipsis) {
          return (
            <Col
              key={data.label}
              span={24 / grid}
              className={classNames(currentParentClassNameNoEllipsis)}
            >
              <span className={`${className}--body--col--label`}>{data.label}</span>
              {data.hasLineBreak ? (
                <span className={currentClassNameNoEllipsis} style={{ whiteSpace: 'pre-wrap' }}>
                  {data.content}
                </span>
              ) : (
                <span className={currentClassNameNoEllipsis}>{data.content}</span>
              )}
            </Col>
          );
        }

        const currentParentClassName = `${className}--body--col`;
        const currentClassName = `${className}--body--col--content`;
        const currentClassNameIndex = `${className}--body--col--content${index}`;

        return (
          <Col key={data.label} span={24 / grid} className={classNames(currentParentClassName)}>
            <span className={`${className}--body--col--label`}>{data.label}</span>
            <Tooltip
              placement='top'
              destroyTooltipOnHide
              title={data.tooltipContent || data.content}
              visible={visible && overClassName === currentClassNameIndex}
            >
              <span
                className={currentClassName}
                onMouseOver={e => {
                  if (inspectEllipsisQuick(e.currentTarget)) {
                    setVisible(true);
                    setOverClassName(currentClassNameIndex);
                  }
                }}
                onMouseLeave={() => {
                  setVisible(false);
                }}
                onFocus={() => {}}
                onBlur={() => {}}
              >
                {data.content}
              </span>
            </Tooltip>
          </Col>
        );
      });
    }
    if (type === 'picture') {
      return (info as { label: string; content: string }[]).map(data => {
        const extraProps = {
          className: classNames({
            [`${className}--body--pic--item--img`]: true,
            [`${className}--body--pic--item--imgNormal`]: true,
          }),
        } as { className: string; href?: string };
        if (data.content) {
          extraProps.className = `${className}--body--pic--item--img`;
          extraProps.href = data.content as string;
        }
        return (
          <div key={data.label} className={`${className}--body--pic--item`}>
            <div>{data.label}</div>
            <a target='_blank' rel='noopener noreferrer' {...extraProps}>
              {data.content && <img src={data.content as string} alt='' />}
            </a>
          </div>
        );
      });
    }
    return [];
  };

  /** 组装尾部信息展示 */
  const FooterItems = useMemo(() => {
    if (!footerInfo) {
      return [];
    }
    return footerInfo.map((data: { label: string; content: string }) => (
      <div
        key={data.label}
        className={classNames(`${className}--body--col`, `${className}--body--col--footer`)}
      >
        <span className={`${className}--body--col--label`}>{data.label}</span>
        {data.content}
      </div>
    ));
  }, [footerInfo]);

  /** list模式下 组装多个基本信息展示 */
  const ListItems = useMemo(() => {
    if (!list) {
      return [];
    }
    if (type === 'list') {
      const Items: JSX.Element[][] = [];
      list.forEach(data => {
        Items.push(
          data.map((child: { label: string; content: string }) => (
            <Col key={child.label} span={24 / grid} className={`${className}--body--col`}>
              <span className={`${className}--body--col--label`}>{child.label}</span>
              {child.content}
            </Col>
          )),
        );
      });
      return Items;
    }
    return [];
  }, [list, type, columns]);

  /** listTable模式下 组装多个表格展示 */
  const ListTable = useMemo(() => {
    if (!list) {
      return [];
    }
    if (type === 'listTable') {
      const Items: JSX.Element[] = [];
      list.forEach((data, index: number) => {
        const { columns: newColumns, scroll } = tableScroll({
          oldColumns: columns,
          dataSource: data.dataSource,
        });
        delete scroll?.y;
        Items.push(
          <div className={`${className}--body--listTable`} key={data.id}>
            {data.title && (
              <div className={`${className}--body--listTable--title`}>{data.title}</div>
            )}
            <div
              className={classNames({
                [`${className}--body--listTable--content`]: true,
                [`${className}--body--listTable--contentLast`]: index === list.length - 1,
              })}
            >
              <XuiListPage
                rowKey={rowKey}
                columns={newColumns}
                propDataSource={data.dataSource}
                closePagination
              />
            </div>
          </div>,
        );
      });
      return Items;
    }
    return [];
  }, [list, type, columns, rowKey]);

  const ListCollapse = useMemo(() => {
    return listCollapseData?.map(item => (
      <div className={`${className}--body--listCollapse`} key={item.title}>
        <Collapse defaultActiveKey={item.canExpand ? ['1'] : []} expandIconPosition='right'>
          <Collapse.Panel
            header={
              <div className={`${className}--body--listCollapse--header`}>
                <span className={`${className}--body--listCollapse--title`}>{item.title}</span>
                {item.headerExtra}
              </div>
            }
            key='1'
            disabled={!item.canExpand}
            showArrow={!!item.canExpand}
          >
            {item.content}
          </Collapse.Panel>
        </Collapse>
      </div>
    ));
  }, [listCollapseData]);

  const { columns: newColumns, scroll } = useMemo(
    () => tableScroll({ oldColumns: columns, dataSource }),
    [dataSource, columns],
  );

  delete scroll?.y;

  return (
    <div
      className={classNames({
        [className]: true,
        [`${className}--border`]: border,
      })}
    >
      {title && (
        <div className={`${className}--head`}>
          <div className={`${className}--head--title`}>{title}</div>
          {buttonGroup && <div className={`${className}--head--buttonGroup`}>{buttonGroup}</div>}
        </div>
      )}
      {extra && <div className={`${className}--extra`}>{extra}</div>}
      <div className={`${className}--body`}>
        {type === 'info' && (
          <Skeleton
            active
            paragraph={{
              rows: info && footerInfo ? Math.round(info?.length / grid + footerInfo?.length) : 4,
            }}
            loading={loading}
          >
            <Row>{getColItems()}</Row>
            {FooterItems}
          </Skeleton>
        )}
        {type === 'table' && (
          <div className={`${className}--body--table`}>
            <XuiListPage
              rowKey={rowKey}
              columns={newColumns}
              propDataSource={dataSource}
              paginationConfig={paginationConfig}
              closePagination={!paginationConfig}
            />
          </div>
        )}
        {type === 'picture' && <div className={`${className}--body--pic`}>{getColItems()}</div>}
        {type === 'picture' && <div className={`${className}--body--pic`}>{getColItems()}</div>}
        {type === 'list' &&
          ListItems.map((data, index) => (
            // eslint-disable-next-line react/no-array-index-key
            <div className={`${className}--body`} key={index}>
              <div className={`${className}--body--head`}>{`${title}${index + 1}`}</div>
              <Row>{data}</Row>
            </div>
          ))}
        {type === 'listTable' && ListTable}
        {type !== 'info' && FooterItems}
        {type === 'listCollapse' && ListCollapse}
      </div>
    </div>
  );
};

export default XuiDetailInformation;
