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';

// ScheLoopList 组件的 Props
export interface ScheLoopListProps {
  roundTabList?: RoundTab[]; // 轮次tab列表
  roundList?: RoundData[]; // 轮次赛程数据
  onRoundChange?: (startIndex: number) => void; // 轮次显示变化回调
  onClickLive?: (schId: string | number) => void; // 点击直播回调
  onClickTeams?: (schId: string | number) => void; // 点击队伍回调
  hasNav?: boolean; // 是否有侧边导航栏（影响边距样式）
  emptyText?: string; // 空状态提示文字
  showEmpty?: boolean; // 是否显示空状态
}

// ScheLoopList 组件的 State
export interface ScheLoopListState {
  currentRoundIndex: number; // 当前轮次索引
  contentScrollLeft: number; // 横向滚动位置
  contentOpacity: number; // 赛程内容透明度 (0 到 1)
}

class ScheLoopList extends Component<ScheLoopListProps, ScheLoopListState> {
  private touchStartX = 0;
  private touchStartY = 0;
  private isSwiping = false;
  private swipeDirection: 'horizontal' | 'vertical' | 'none' = 'none';

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

  // 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;
  };

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

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

    // 检查是否在合理范围内（-10000 到 10000，覆盖绝大多数屏幕尺寸）
    // 异常值通常是很大的负数或正数（如 -1275068303）
    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 };
  };

  // 处理 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(3.62); // 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;

    // 计算当前显示的三个轮次的索引范围
    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,
      hasNav = false,
      emptyText = '两个以上队伍报名后将在此显示预览赛程',
      showEmpty = false,
    } = this.props;

    return (
      <div className={`${styles['sche-loop-list']} ${hasNav ? styles['sche-loop-list-has-nav'] : ''}`}>
        {/* 赛程轮次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.84)}px` : `${this.remToPx(4.7)}px`,
            }}
          >
            {
              roundList.map((round, roundIndex) => (
                <div
                  className={styles['content-item']}
                  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}
                        onClickLive={onClickLive}
                        onClickTeams={onClickTeams}
                      />
                    </div>
                  ))}
                  {roundIndex !== roundList.length - 1 && <div className={styles['sche-item-line']}></div>}
                </div>
              ))
            }
          </div>
        </div>
        )}
        {/* 空状态 */}
        {roundList.length === 0 && showEmpty && (
        <div className={styles.content}>
          <Empty text={emptyText} />
        </div>
        )}
      </div>
    );
  }
}

export default ScheLoopList;
