import { GameletAPI } from 'gamelet-pixui-frame';
import { h, Component } from 'preact';

import Empty from '../empty/empty';
import ScheItem from '../sche-item/sche-item';
import { RoundTab, RoundData } from '../sche-item/types';

import styles from './css/index.less';

// ScheTreeList 的 Props
export interface ScheTreeListProps {
  roundTabList?: RoundTab[]; // 轮次tab列表
  roundList?: RoundData[]; // 赛程列表
  onClickLive?: (schId: string | number) => void; // 点击直播回调
  onClickTeams?: (schId: string | number) => void; // 点击队伍回调
  onRoundChange?: (index: number) => void; // 轮次变化回调
  emptyText?: string; // 空状态提示文字
  showEmpty?: boolean; // 是否显示空状态
}

// ScheTreeList 的 State
export interface ScheTreeListState {
  currentRoundIndex: number; // 当前轮次索引
  contentScrollLeft: number; // 横向滚动位置
  contentOpacity: number; // 内容透明度
}

class ScheTreeList extends Component<ScheTreeListProps, ScheTreeListState> {
  private touchStartX = 0;
  private touchStartY = 0;
  private isSwiping = false;
  private swipeDirection: 'horizontal' | 'vertical' | 'none' = 'none';

  constructor(props: ScheTreeListProps) {
    super(props);
    this.state = {
      currentRoundIndex: 0, // 初始轮次索引
      contentScrollLeft: 0, // 初始横向滚动位置
      contentOpacity: 1, // 初始透明度为1
    };
  }

  // 重置赛程轮次tab到最左边
  resetRoundPosition = () => {
    this.setState({
      currentRoundIndex: 0,
      contentScrollLeft: 0,
      contentOpacity: 1,
    });
  };

  // 检查坐标是否为异常值
  isValidCoordinate = (value: number): boolean => {
    if (typeof value !== 'number' || isNaN(value) || !isFinite(value)) {
      return false;
    }
    if (value < -10000 || value > 10000) {
      return false;
    }
    return true;
  };

  // 获取事件坐标（真机用触摸，模拟器用鼠标，与绑定策略一致）
  getEventCoordinates = (e: any) => {
    const clientX = e?.targetTouches ? e?.targetTouches?.[0]?.clientX : e?.clientX;
    const clientY = e?.targetTouches ? e?.targetTouches?.[0]?.clientY : e?.clientY;
    const x = this.isValidCoordinate(clientX) ? clientX : window.innerWidth / 2;
    const y = this.isValidCoordinate(clientY) ? clientY : window.innerHeight / 2;
    return { clientX: x, clientY: y };
  };

  // rem转px
  remToPx = (remValue: number): number => {
    const width = window.innerWidth;
    const height = window.innerHeight;
    const base = Math.min(height, width);
    let fontSize: number;

    if (base > 720) { // 兼容ipad
      fontSize = 80;
    } else if (base === 720 && width < 1280) {
      fontSize = 70;
    } else {
      fontSize = 100 * (base / 750);
    }

    return remValue * fontSize;
  };

  // 处理 content-box 的触摸开始
  handleContentTouchStart = (e) => {
    const { clientX, clientY } = this.getEventCoordinates(e);

    this.touchStartX = clientX;
    this.touchStartY = clientY;
    this.isSwiping = false;
    this.swipeDirection = 'none';

    console.log('触摸开始 - startX:', clientX, 'startY:', clientY);
  };

  // 处理 content-box 的触摸移动
  handleContentTouchMove = (e) => {
    const { clientX, clientY } = this.getEventCoordinates(e);

    // 如果还没有确定滑动方向
    if (this.swipeDirection === 'none') {
      const deltaX = Math.abs(clientX - this.touchStartX);
      const deltaY = Math.abs(clientY - this.touchStartY);

      // 滑动距离达到阈值后才判断方向，避免误判
      if (deltaX > 10 || deltaY > 10) {
        console.log('达到阈值，判断方向 - deltaX/deltaY:', (deltaX / deltaY).toFixed(2));

        // 判断滑动方向：横向移动距离明显大于纵向（至少1.5倍）
        if (deltaX > deltaY * 1.5) {
          this.swipeDirection = 'horizontal';
          this.isSwiping = true;
          console.log('✅ 判定为横向滑动');
        } else if (deltaY > deltaX * 1.5) {
          // 明确判定为纵向滑动
          this.swipeDirection = 'vertical';
          this.isSwiping = false;
          console.log('✅ 判定为纵向滑动');
        } else {
          console.log('⏸️ 方向不明确，继续等待');
        }
      }
    }

    // 只有在横向滑动时才阻止默认行为
    if (this.swipeDirection === 'horizontal' && this.isSwiping) {
      e.preventDefault();
    }
  };

  // 处理 content-box 的触摸结束
  handleContentTouchEnd = (e) => {
    console.log('触摸结束 - isSwiping:', this.isSwiping, 'swipeDirection:', this.swipeDirection);

    // 只有在确定是横向滑动时才处理轮次切换
    if (!this.isSwiping || this.swipeDirection !== 'horizontal') {
      this.isSwiping = false;
      this.swipeDirection = 'none';
      return;
    }

    const { clientX, clientY } = this.getEventCoordinates(e);

    const deltaX = clientX - this.touchStartX;
    const deltaY = clientY - this.touchStartY;
    const threshold = 300; // 滑动阈值，单位：px

    console.log('触摸结束位置 - endX:', clientX, 'endY:', clientY, 'deltaX:', deltaX, 'deltaY:', deltaY);

    // 要求横向移动距离大于阈值，且横向移动明显大于纵向移动（至少2倍）
    if (Math.abs(deltaX) > threshold && Math.abs(deltaX) > Math.abs(deltaY) * 2) {
      console.log('✅ 达到切换阈值，准备切换轮次');
      const itemWidth = this.remToPx(4.33); // rem
      const { currentRoundIndex } = this.state;
      const roundTabList = this.props.roundTabList || [];
      const maxIndex = roundTabList.length - 3;
      if (deltaX < 0) {
        // 向左滑动，显示下一轮
        if (currentRoundIndex < maxIndex) {
          const newIndex = currentRoundIndex + 1;
          const newScrollLeft = newIndex * itemWidth;
          console.log('👉 向左滑动，切换到下一轮:', newIndex);
          this.setState({
            currentRoundIndex: newIndex,
            contentScrollLeft: newScrollLeft,
          }, (() => {
            this.notifyRoundChange();
          }));
        }
      } else {
        // 向右滑动，显示上一轮
        if (currentRoundIndex > 0) {
          const newIndex = currentRoundIndex - 1;
          const newScrollLeft = newIndex * itemWidth;
          console.log('👈 向右滑动，切换到上一轮:', newIndex);
          this.setState({
            currentRoundIndex: newIndex,
            contentScrollLeft: newScrollLeft,
          }, (() => {
            this.notifyRoundChange();
          }));
        }
      }
    } else {
      console.log('❌ 未达到切换阈值，不切换轮次');
    }

    this.isSwiping = false;
    this.swipeDirection = 'none';
  };

  // 通知轮次显示变化
  notifyRoundChange = () => {
    const { currentRoundIndex } = this.state;

    // 计算当前显示的三个轮次的索引范围
    // 假设显示窗口是3个轮次，以 currentRoundIndex 为中心显示
    const startIndex = currentRoundIndex;
    console.log('startIndex', startIndex);
    this.setState({
      contentOpacity: 0,
    }, (() => {
      this.props?.onRoundChange?.(startIndex);
      setTimeout(() => {
        this.setState({
          contentOpacity: 1,
        });
      }, 500);
    }));
    // 回调给父组件
  };

  render() {
    const {
      roundTabList = [],
      roundList = [],
      onClickLive,
      onClickTeams,
      emptyText = '两个以上队伍报名后将在此显示预览赛程',
      showEmpty = false,
    } = this.props;

    return (
      <div className={styles['sche-tree-list']}>
        {/* 赛程轮次tab */}
        {roundTabList.length > 0 && (
        <div className={styles['content-tab']}>
          <div
            className={styles['content-tab-wrap']}
            style={{
              left: `-${this.state.contentScrollLeft}px`,
            }}
          >
            {roundTabList.map((item, index) => (
              <div
                className={`${styles['content-tab-item']} ${item.status === 'end' ? styles.ended : ''} ${item.status === 'ing' ? styles['in-progress'] : ''}`}
                key={index}
              >
                <div className={styles['content-tab-item-line']}></div>
                <div className={styles['content-tab-item-dot']}></div>
                <div className={styles['content-tab-item-text']}>{item.name}
                  {item.showIngTag && <div className={styles['content-tab-item-tag']}><text className={styles['content-tab-item-tag-text']}>进行中</text></div>}
                </div>
              </div>
            ))}
          </div>
        </div>
        )}
        {/* 赛程内容 */}
        {roundList.length > 0 && (
        <div
          className={styles.content}
          id="content-box"
          {...(GameletAPI.getRuntimeEnv() === 'PxIDE' && {
            onMouseDown: this.handleContentTouchStart,
            onMouseMove: this.handleContentTouchMove,
            onMouseUp: this.handleContentTouchEnd,
          })}
          onTouchStart={this.handleContentTouchStart}
          onTouchMove={this.handleContentTouchMove}
          onTouchEnd={this.handleContentTouchEnd}
          onTouchCancel={this.handleContentTouchEnd}
        >
          <div
            className={styles['content-wrap']}
            style={{
              height: roundList[0] ? `${roundList[0].list.length * this.remToPx(1.6)}px` : `${this.remToPx(4.7)}px`,
            }}
          >
            {
              roundList.map((round, roundIndex) => {
                // 兼容双败淘汰赛赛程
                // 判断 roundList 长度是否小于等于3，并根据 list 长度关系添加对应的类名
                let additionalClass = '';
                if (roundList.length <= 3) {
                  // 前两个 round.list 的长度一样，给 content-item-loser1
                  if (roundList[0] && roundList[1] && roundList[0].list.length === roundList[1].list.length) {
                    additionalClass = styles['content-item-loser1'];
                  } else if (roundList[1] && roundList[2] && roundList[1].list.length === roundList[2].list.length) {
                    // 后两个 round.list 的长度一样，给 content-item-loser2
                    additionalClass = styles['content-item-loser2'];
                  }
                }

                return (
                  <div
                    className={`${styles['content-item']} ${additionalClass}`}
                    key={roundIndex}
                  >
                    {round.list.map((match, matchIndex) => (
                      <div
                        className={styles['sche-item']}
                        key={matchIndex}
                      >
                        <ScheItem
                          schId={match.schId}
                          teamA={match.teamA}
                          teamB={match.teamB}
                          tips={match.tips}
                          status={match.status}
                          scheCodeName={match.scheCodeName}
                          onClickLive={onClickLive}
                          onClickTeams={onClickTeams}
                        />
                        <div className={styles['sche-item-line']}><div className={styles['sche-item-line-inner']}></div></div>
                      </div>
                    ))}
                  </div>
                );
              })
            }
          </div>
        </div>
        )}
        {/* 空状态 */}
        {roundList.length === 0 && showEmpty && (
        <div className={styles.content}>
          <Empty text={emptyText} />
        </div>
        )}
      </div>
    );
  }
}

export default ScheTreeList;
