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

import CdnImage from '../cdn-image/cdn-image';
import Empty from '../empty/empty';
import ScheChampoin from '../sche-champoin/sche-champoin';
import ScheItem from '../sche-item/sche-item';
import {
  BaseScheContainerProps,
  BaseScheContainerState,
  ChampoinScheduleItem,
} from '../sche-item/types';

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

// ScheTree 特有的 Props（继承基础 Props）
export interface ScheTreeProps extends BaseScheContainerProps {
  showChampoinSchedule?: boolean; // 是否显示冠军赛程
  champoinSchedule?: ChampoinScheduleItem; // 冠军总决赛赛程
}

// ScheTree 的 State（使用基础 State）
export type ScheTreeState = BaseScheContainerState;

class ScheTree extends Component<ScheTreeProps, ScheTreeState> {
  private sliderListRef: HTMLDivElement | null = null;
  private startY = 0;
  private startPosition = 0;
  private touchStartX = 0;
  private touchStartY = 0;
  private isSwiping = false;
  private swipeDirection: 'horizontal' | 'vertical' | 'none' = 'none';

  constructor(props: ScheTreeProps) {
    super(props);
    this.state = {
      sliderPosition: 0, // 初始位置在顶部
      isDragging: false,
      currentGroupIndex: 1, // 初始为第1组
      contentScrollLeft: 0, // 初始横向滚动位置
      currentRoundIndex: 0, // 初始轮次索引
      contentOpacity: 1, // 初始透明度为1
    };
  }


  // 计算当前分组索引
  calculateGroupIndex = (position: number): number => {
    const groupCount = this.props.groupCount || 10;
    // position 范围是 0 到 1
    // 将其映射到 1 到 groupCount
    const index = Math.floor(position * groupCount) + 1;
    return Math.min(index, groupCount);
  };

  // 开始拖拽
  handleDragStart = (e: any) => {
    e.preventDefault();
    e.stopPropagation();

    const clientY = e.targetTouches ? e.targetTouches[0].clientY : e.clientY;

    this.startY = clientY;
    this.startPosition = this.state.sliderPosition;

    this.setState({ isDragging: true });
  };

  // 拖拽中
  handleDragMove = (e: any) => {
    if (!this.state.isDragging || !this.sliderListRef) return;

    e.preventDefault();

    const clientY = e.targetTouches ? e.targetTouches[0].clientY : e.clientY;

    const deltaY = clientY - this.startY;

    // 获取滑块轨道的高度
    const trackHeight = this.sliderListRef.clientHeight;
    const sliderHeight = 1.01 * parseFloat(getComputedStyle(document.documentElement).fontSize); // 1.01rem
    const maxTravel = trackHeight - sliderHeight;

    // 计算新位置 (0 到 1)
    const deltaPosition = deltaY / maxTravel;
    let newPosition = this.startPosition + deltaPosition;

    // 限制在 0 到 1 之间
    newPosition = Math.max(0, Math.min(1, newPosition));

    const newGroupIndex = this.calculateGroupIndex(newPosition);

    this.setState({
      sliderPosition: newPosition,
      currentGroupIndex: newGroupIndex,
    });
  };

  // 结束拖拽
  handleDragEnd = () => {
    this.setState({ isDragging: false });
    this.props.selectGroup?.(this.state.currentGroupIndex);
  };

  // 重置赛程轮次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 };
  };

  // 处理 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();
    }
  };
  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 的触摸结束
  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 {
      typeTabs = [],
      activeTab = 'main',
      onTabChange,
      roundTabList = [],
      roundList = [],
      myScheNum,
      groupCount = 5,
      showMySche,
      onMyScheClick,
      title = '全部赛程',
      onBackClick,
      onClickLive,
      onClickTeams,
      battleNavList = [],
      activeIndex = 0,
      navClick,
      groupTabs = [],
      activeGroupTab = 1,
      onGroupTabChange,
      showSubscribe = false,
      onSubscribeClick,
      subscribeStatus = 'subscribed',
      showChampoinSchedule = false,
      champoinSchedule = {
        teamA: { name: '', img: '', score: '' },
        teamB: { name: '', img: '', score: '' },
        tips: '',
        status: 'waiting',
        schId: '',
        subscribeStatus: 'subscribed',
        onChampoinClickLive: () => {},
        onChampoinClickTeams: () => {},
        onChampoinSubscribeClick: () => {},
      },
      showEmpty = false,
    } = this.props;

    return (
      <div className={styles['sche-tree']}>
        <div className={`${styles['sche-tree-wrap']} ${battleNavList?.length > 0 ? styles['sche-tree-wrap-nav'] : ''}`} >
          {/* 顶部标题和切换我的赛程按钮 */}
          <div className={styles.header}>
            <div className={styles['header-left']}>
              <div
                className={styles['btn-back']}
                onClick={onBackClick}
              />
              <div className={styles.title}>{title}</div>
            </div>
            {showMySche && (
            <div
              className={styles['btn-my-sche']}
              onClick={onMyScheClick}
            >
              <div className={styles['btn-my-sche-text']}>我的赛程：当前至少还有<text className={styles['btn-my-sche-text-number']}>{myScheNum}</text>场比赛
                <CdnImage
                  className={styles['btn-my-sche-icon']}
                  src="https://image-1251917893.file.myqcloud.com/Esports/schedule/next-icon.png"
                />
              </div>
            </div>
            )}
            {showSubscribe && (
            <div
              className={styles['btn-my-sche']}
              onClick={onSubscribeClick}
            >
              <div className={styles['btn-my-sche-text']}>
                <CdnImage
                  className={styles['btn-subscribe-icon']}
                  src={subscribeStatus === 'subscribed' ? 'https://image-1251917893.file.myqcloud.com/Esports/schedule/subscribe-icon.png' : 'https://image-1251917893.file.myqcloud.com/Esports/schedule/unsubscribe-icon.png'}
                />
                {subscribeStatus === 'subscribed' ? '订阅比赛' : '取消订阅'}
              </div>
            </div>
            )}
          </div>
          <div className={styles['sche-tree-content-wrap']}>
            {/* 侧边栏 */}
            {battleNavList?.length > 0 && (
            <div className={styles['reward-page-bar']}>
              {battleNavList?.map((item, index) => (
                <div
                  key={index}
                  className={`${styles['reward-page-bar-item']} ${activeIndex === item.id ? styles['item-active'] : ''}`}
                  onClick={() => navClick?.(item.id)}
                ><text className={styles['reward-page-bar-text']}> {item.title}</text>
                </div>
              ))}
            </div>
            )}
            <div className={styles['tab-switch-right']}>
              {/* 赛程分类tab切换 */}
              {typeTabs.length > 0 && (
              <div className={styles['tab-switch-wrap']}>
                <div className={styles['tab-switch']}>
                  {typeTabs.map(tab => (
                    <div
                      key={tab.value}
                      className={`${styles['tab-item']} ${activeTab === tab.value ? styles['tab-active'] : ''}`}
                      onClick={() => onTabChange?.(tab.value)}
                    >
                      <text className={styles['tab-item-text']}>{tab.name}</text>
                    </div>
                  ))}
                </div>
              </div>
              )}
              {/* 分组tab */}
              {groupTabs.length > 0 && (
              <div className={styles['group-tab-switch-wrap']}>
                <div className={styles['group-tab-switch']}>
                  {groupTabs.map(tab => (
                    <div
                      key={tab.value}
                      className={`${styles['group-tab-item']} ${activeGroupTab === tab.value ? styles['group-tab-active'] : ''}`}
                      onClick={() => onGroupTabChange?.(tab.value)}
                    >
                      <text className={styles['group-tab-item-text']}>{tab.title}</text>
                    </div>
                  ))}
                </div>
              </div>
              )}
              {/* 赛程轮次tab */}
              {roundTabList.length > 0 && !showChampoinSchedule && (
              <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 && !showChampoinSchedule && (
              <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) => (
                      <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 className={styles['sche-item-line']}><div className={styles['sche-item-line-inner']}></div></div>
                          </div>
                        ))}
                      </div>
                    ))
                  }
                </div>
              </div>
              )}
              {/* 空状态 */}
              {(roundList.length === 0 && !showChampoinSchedule && showEmpty) && (
              <div className={styles.content}>
                <Empty text="两个以上队伍报名后将在此显示预览赛程" />
              </div>
              )}
              {/* 冠军总决赛 */}
              {showChampoinSchedule && champoinSchedule && (
                <ScheChampoin
                  schId={champoinSchedule.schId}
                  teamA={champoinSchedule.teamA}
                  teamB={champoinSchedule.teamB}
                  tips={champoinSchedule.tips}
                  status={champoinSchedule.status}
                  subscribeStatus={champoinSchedule.subscribeStatus}
                  onChampoinClickLive={champoinSchedule.onChampoinClickLive}
                  onChampoinClickTeams={champoinSchedule.onChampoinClickTeams}
                  onChampoinSubscribeClick={champoinSchedule.onChampoinSubscribeClick}
                  showVsTag={champoinSchedule.showVsTag}
                />
              )}
              {/* 分组滑块 */}
              {groupCount && groupCount > 1 && (
              <div className={styles['group-slider']}>
                <div
                  className={styles['group-slider-list']}
                  ref={(ref) => {
                    this.sliderListRef = ref;
                  }}
                >
                  <div
                    className={styles['group-slider-item']}
                    id="group-slider-item"
                    style={{
                      top: `${this.state.sliderPosition * 100}%`,
                      transform: `translateY(-${this.state.sliderPosition * 100}%)`,
                      cursor: this.state.isDragging ? 'grabbing' : 'grab',
                    }}
                    onMouseDown={this.handleDragStart}
                    onMouseUp={this.handleDragEnd}
                    onMouseMove={this.handleDragMove}
                    onMouseOut={this.handleDragEnd}
                    onTouchStart={this.handleDragStart}
                    onTouchMove={this.handleDragMove}
                    onTouchEnd={this.handleDragEnd}
                    onTouchCancel={this.handleDragEnd}
                  >
                    <div className={styles['group-slider-item-inner']}>
                      <div className={styles['group-slider-item-text']}>
                      </div>
                    </div>
                  </div>
                </div>
                <div className={styles['group-slider-number']}>{this.state.currentGroupIndex}/{groupCount}</div>
              </div>
              )}
            </div>
          </div>
        </div>
      </div>
    );
  }
}

export default ScheTree;

