import React, { ReactNode, useEffect, useMemo, useRef, useState } from 'react';
import { localeable, LocaleProps } from '../locale';
import { SchemaExpression } from '../Schema';
import { themeable, ThemeProps } from '../theme';
import { Icon } from './icons';

export interface TimelineItemProps {
  /**
   * 时间点
   */
  time: string;

  /**
   * 事件名称
   */
  title?: string | ReactNode;

  /**
   * 详细内容
   */
  detail?: string;

  /**
   * detail折叠时文案
   */
  detailCollapsedText?: string;

  /**
   * detail展开时文案
   */
  detailExpandedText?: string;

  /**
   * 时间点圆圈颜色,可传入英文/颜色值/level样式（info、success、warning、danger）
   */
  color?: SchemaExpression;

  /**
   * 图标
   */
  icon?: string | ReactNode;

  /**
   * 时间线线颜色
   */
  lineColor?: SchemaExpression;

  /**
   * 方向 纵向/横向
   */
  direction?: 'vertical' | 'horizontal';

  // 时间线组件触发事件唯一的key
  TimelineUniqueKey: string;
  // 横向数据都没有主标题的时候，把高度占位给去掉
  allDataHasNoLabel?: boolean;
}

export interface TimelineItem
  extends ThemeProps,
  LocaleProps,
  TimelineItemProps {
  key: string;
}

export function TimelineItem(props: TimelineItem) {
  const {
    time,
    title,
    detail,
    detailCollapsedText,
    detailExpandedText,
    lineColor,
    direction,
    color,
    icon,
    classnames: cx,
    translate: __,
    key,
    TimelineUniqueKey,
    allDataHasNoLabel
  } = props;

  const [detailVisible, setDetailVisible] = useState<boolean>(false);
  const detailVisibleRef = useRef<boolean>(false);
  const [showDetailBtn, setShowDetailBtn] = useState<boolean>(true);
  const timelineItemRef = useRef<HTMLDivElement>(null);
  const detailTextRef = useRef<HTMLDivElement>(null);
  // const isVertical = useMemo(() => direction === 'vertical', [direction]);
  const renderDetail = (
    detail: string,
    detailCollapsedText: string = __('Timeline.collapseText'),
    detailExpandedText: string = __('Timeline.expandText')
  ): ReactNode => {
    return (
      <>
        <div
          className={cx('TimelineItem-detail-button')}
          onClick={() => {setDetailVisible(!detailVisible); detailVisibleRef.current = !detailVisibleRef.current}}
        >
          {detailVisible ? detailExpandedText : detailCollapsedText}
          <div
            className={cx(
              'TimelineItem-detail-arrow',
              `${detailVisible && 'TimelineItem-detail-arrow-top'}`
            )}
          >
            <Icon icon="tree-down" />
          </div>
        </div>
        {/* {!isVertical ? <div
          className={cx(
            `${detailVisible
              ? 'TimelineItem-detail-visible'
              : 'TimelineItem-detail-invisible'
            }`
          )}
        >
          {detail}
        </div> : null
        } */}
      </>
    );
  };

  // 判断是否为颜色值
  const isColorVal = color && /^#([0-9a-fA-F]{6}|[0-9a-fA-F]{3})$/.test(color);
  // 时间线线颜色
  const isLineColorVal = lineColor && /^#([0-9a-fA-F]{6}|[0-9a-fA-F]{3})$/.test(lineColor);
  // 取level级颜色
  const levelColor = !isColorVal && color;
  // 时间线层级颜色
  const lineLevelColor = !isLineColorVal && lineColor;

  const genStyle = (color: string | undefined) => {
    const directionStyle = direction?.trim() === 'horizontal' ? 'to right,' : '';
    return color ? {
      backgroundImage: `linear-gradient(${directionStyle}${color} 50%, rgba(255, 255, 255, 0) 0%)`
    } : {}
  }
  const handleResizeWidth = () => {
    if (detailTextRef.current) {
      if (!detailVisibleRef.current) {
        const { clientHeight, scrollHeight } = detailTextRef.current;
        setShowDetailBtn(clientHeight > 34 && scrollHeight > clientHeight);
      }
    }
  }
  useEffect(() => {
    if (timelineItemRef.current && detail) {
      document.body.addEventListener(TimelineUniqueKey, handleResizeWidth)
      requestAnimationFrame(handleResizeWidth);
    }
    return () => {
      document.body.removeEventListener(TimelineUniqueKey, handleResizeWidth);
    }
  }, []);
  return (
    <div ref={timelineItemRef} className={cx('TimelineItem')} key={key}>
      <div className={cx('TimelineItem-axle')}>
        <div className={cx('TimelineItem-line', lineLevelColor && `TimelineItem-line--${lineLevelColor}`)}
          style={genStyle(isLineColorVal ? lineColor : undefined)}
        ></div>
        {icon ? (
          <div className={cx('TimelineItem-icon')}>
            <Icon icon={icon} style={{color : isColorVal ? color : undefined}} />
          </div>
        ) : (
          <div
            className={cx(
              'TimelineItem-round',
              levelColor && `TimelineItem-round--${levelColor}`
            )}
            style={isColorVal ? { backgroundColor: color } : undefined}
          ></div>
        )}
      </div>
      <div className={cx('TimelineItem-content')}>
        <div className={cx('TimelineItem-title')} style={allDataHasNoLabel ?{height:  0 }: {}}>{title}</div>
        <div className={cx('TimelineItem-time')}>{time}</div>
        <div className={cx('TimelineItem-detail-text', detailVisible ? 'visible' : '')} ref={detailTextRef}>{detail}</div>
        {detail && showDetailBtn && (
          <div className={cx('TimelineItem-detail')}>
            {renderDetail(detail, detailCollapsedText, detailExpandedText)}
          </div>
        )}
      </div>
    </div>
  );
}

export default themeable(localeable(TimelineItem));
