import React, { useEffect, useRef, useState } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import styles from "./index.module.scss";
import { RankItem, getRankList } from "../../utils/API";

const sortDESC = (arr: RankItem[]) => {
  arr.sort((a, b) => {
    if (a.score !== b.score) {
      // 得分不同时，得分高的排在前面
      return b.score - a.score;
    } else {
      // 得分相同时，花费时间少的排在前面
      return a.time - b.time;
    }
  });
  // 为排序后的数据添加排名信息
  arr.forEach((item, index) => {
    item.rank = index + 1;
  });

  // 降序
  arr.reverse();
  return arr;
};

const Rank = () => {
  const navigate = useNavigate();
  const [rankList, setRankList] = useState<RankItem[]>([]);
  const [currentUser, setCurrentUser] = useState<number>(0);
  const topThree = ["探花", "榜眼", "状元"];
  const containerRef = useRef<HTMLDivElement>(null);
  const { noRank, phone } = useLocation().state as { noRank: boolean; phone?: number } || { noRank: false };

  useEffect(() => {
    getRankList().then((res) => {
      setRankList(sortDESC(res.data.data));
      // 找到最大id
      const maxId = Math.max(...res.data.data.map((item: RankItem) => item.id));
      if (noRank) {
        setCurrentUser(res.data.data[res.data.data.length - 1].id);
      } else {
        const rankMe = res.data.data.find((item: RankItem) => item.phone === phone?.toString())
        // 是否在榜
        if (rankMe) {
          setCurrentUser(rankMe.id);
          return
        }
        setCurrentUser(maxId);
      }
    });
    // 一开始就滚到当前用户
    const checkContainer = setInterval(() => {
      const container = document.querySelector(".rank-focus-item");
      if (container) {
        container.scrollIntoView({ behavior: "smooth", inline: "end", block: "nearest" });
        clearInterval(checkContainer); // 找到后清除定时器
      }
    }, 200);

    containerRef.current = document.querySelector(".container")!;
  }, [noRank, phone]);

  // 滚轮让x轴滚动
  const handleWheel = (event: React.WheelEvent<HTMLDivElement>) => {
    if (containerRef.current) {
      containerRef.current.scrollLeft = containerRef.current.scrollLeft + event.deltaY;
    }
  };


  const activeRank = rankList.find((item) => item.id === currentUser)?.rank!;
  const handleLeft = () => {
    if (activeRank < rankList.length) {
      setCurrentUser(rankList.find((item) => item.rank === activeRank + 1)!.id);
      if (containerRef.current) {
        const target = containerRef.current.querySelector(".rank-focus-item");
        if (target) {
          target.scrollIntoView({ behavior: "smooth", inline: "end", block: "nearest" });
        }
      }
    }
  };

  const handleRight = () => {
    if (activeRank > 1) {
      setCurrentUser(rankList.find((item) => item.rank === activeRank - 1)!.id);
      if (containerRef.current) {
        const target = containerRef.current.querySelector(".rank-focus-item");
        if (target) {
          target.scrollIntoView({ behavior: "smooth", inline: "start", block: "nearest" });
        }
      }
    }
  };

  return (
    <div className={styles.rank}>
      <img className="title" src={require("../../assets/img/rank_title.png")} alt="rank_title" />
      <div className="content">
        <img className="left" onClick={handleLeft} src={require("../../assets/img/rank_left.png")} alt="rank_left" />
        <div className="container" onWheel={handleWheel}>
          <div className="container-item">
            {rankList.map((item, index) => (
              <div className={`rank-item ${item.id === currentUser ? `rank-focus-item ${item.phone === phone?.toString() ? 'rank-item-active' : ''}` : ""}`} key={index} >
                <div className="rank-title">{index >= rankList.length - 3 ? topThree[index - (rankList.length - 3)] : `第${item.rank}名`} </div>
                <div className="nickname">{item.name}</div>
                <div className="score">获得{item.score}分</div>
                <div className="time">耗时{item.time}秒</div>
                <div className="current-rank">当前排名</div>
              </div>
            ))}
          </div>
        </div>
        <img className="right" onClick={handleRight} src={require("../../assets/img/rank_right.png")} alt="rank_right" />
      </div>
      <div className="btn-group">
        <div className="item " onClick={() => navigate("/")}>返回首页</div>
        <div className="item" onClick={() => navigate("/question")}>重新开始</div>
      </div>
    </div>
  );
};

export default Rank;
