import React, { useState, useEffect, useCallback } from "react";
import { View, Text, Image, ScrollView } from "@tarojs/components";
import Taro, { useDidShow } from "@tarojs/taro";
import "./index.scss";
import GuideBar from "@/components/GuideBar";
import { UserInfoCard } from "@/components/UserInfo/index";
import { UserService, UserInfo } from "@/services/userService";
import ListContainer from "@/container/listContainer";
import { TennisMatch } from "@/../types/list/types";
import { withAuth, NTRPTestEntryCard } from "@/components";
import { EvaluateScene } from "@/store/evaluateStore";
import { useUserInfo } from "@/store/userStore";
import { usePickerOption } from "@/store/pickerOptionsStore";

const MyselfPage: React.FC = () => {
  const pickerOption = usePickerOption();
  // 获取页面参数
  const instance = Taro.getCurrentInstance();
  const user_id = instance.router?.params?.userid || "";

  // 判断是否为当前用户
  const is_current_user = !user_id;

  // 直接从store获取用户信息，确保响应式更新
  const user_info = useUserInfo();

  // 球局记录状态
  const [game_records, set_game_records] = useState<TennisMatch[]>([]);
  // 往期球局
  const [ended_game_records, setEndedGameRecords] = useState<TennisMatch[]>([]);
  const [loading, set_loading] = useState(false);

  // 关注状态
  const [is_following, setIsFollowing] = useState(false);

  // 当前激活的标签页
  const [active_tab, setActiveTab] = useState<"hosted" | "participated">(
    "hosted"
  );

  // 加载用户数据
  // const load_user_data = async () => {
  //   try {
  //     set_loading(true);

  //     // 获取用户信息（包含统计数据）
  //     const user_data = await UserService.get_user_info();
  //     set_user_info(user_data);
  //     // let games_data;
  //     // if (active_tab === "hosted") {
  //     //   games_data = await UserService.get_hosted_games(user_id);
  //     // } else {
  //     //   games_data = await UserService.get_participated_games(user_id);
  //     // }
  //     // set_game_records(games_data);
  //   } catch (error) {
  //     console.error("加载用户数据失败:", error);
  //     Taro.showToast({
  //       title: "加载失败，请重试",
  //       icon: "error",
  //       duration: 2000,
  //     });
  //   } finally {
  //     set_loading(false);
  //   }
  // };

  useEffect(() => {
    pickerOption.getCities();
    pickerOption.getProfessions();
  }, []);

  // 页面加载时获取数据
  // useEffect(() => {
  //   load_user_data();
  // }, [user_id]);

  useDidShow(() => {
    // set_user_info(useUserInfo()); // 确保从编辑页面返回时刷新数据
  });

  // 分类球局数据（使用 useCallback 包装，避免每次渲染都创建新函数）
  const classifyGameRecords = useCallback((
    game_records: TennisMatch[]
  ): { notEndGames: TennisMatch[]; finishedGames: TennisMatch[] } => {
    const now = new Date().getTime();
    return game_records.reduce(
      (result, cur) => {
        let { end_time } = cur;
        end_time = end_time.replace(/\s/, "T");
        new Date(end_time).getTime() > now
          ? result.notEndGames.push(cur)
          : result.finishedGames.push(cur);
        return result;
      },
      {
        notEndGames: [] as TennisMatch[],
        finishedGames: [] as TennisMatch[],
      }
    );
  }, []);

  // 加载球局数据（使用 useCallback 包装，避免每次渲染都创建新函数）
  const load_game_data = useCallback(async () => {
    try {
      let games_data;
      if (active_tab === "hosted") {
        games_data = await UserService.get_hosted_games(user_info.id);
      } else {
        games_data = await UserService.get_participated_games(user_info.id);
      }
      const sorted_games = games_data.sort((a, b) => {
        return (
          new Date(a.original_start_time.replace(/\s/, "T")).getTime() -
          new Date(b.original_start_time.replace(/\s/, "T")).getTime()
        );
      });
      const { notEndGames, finishedGames } = classifyGameRecords(sorted_games);
      set_game_records(notEndGames);
      setEndedGameRecords(finishedGames);
      // set_game_records(games_data);
    } catch (error) {
      console.error("加载球局数据失败:", error);
    }
  }, [active_tab, user_info, classifyGameRecords]);

  // 切换标签页时重新加载球局数据
  useEffect(() => {
    if (!loading) {
      load_game_data();
    }
  }, [loading, load_game_data]);

  // 处理关注/取消关注
  const handle_follow = async () => {
    try {
      const new_following_state = await UserService.toggle_follow(
        user_id,
        is_following
      );
      setIsFollowing(new_following_state);

      Taro.showToast({
        title: new_following_state ? "关注成功" : "已取消关注",
        icon: "success",
        duration: 1500,
      });
    } catch (error) {
      console.error("关注操作失败:", error);
      Taro.showToast({
        title: "操作失败，请重试",
        icon: "error",
        duration: 2000,
      });
    }
  };

  const goPublish = () => {
    Taro.navigateTo({
      url: "/publish_pages/publishBall/index",
    });
  };

  // 处理球局订单
  const handle_game_orders = () => {
    Taro.navigateTo({
      url: "/order_pages/orderList/index",
    });
  };

  // 处理钱包
  const handle_wallet = () => {
    Taro.navigateTo({
      url: "/user_pages/wallet/index",
      // url: "/user_pages/other/index?userid=16",
    });
  };

  const handleOnTab = (tab) => {
    setActiveTab(tab);
  };

  return (
    <View className="myself_page">
      {/* 主要内容 */}
      <View className="myself_main_content">
        {/* 用户信息区域 */}
        <View className="user_info_section">
          <UserInfoCard
            user_info={user_info}
            is_current_user={is_current_user}
            is_following={is_following}
            on_follow={handle_follow}
            onTab={handleOnTab}
          />
          {/* 球局订单和收藏功能 */}
          <View className="quick_actions_section">
            <View className="action_card">
              <View className="action_content" onClick={handle_game_orders}>
                <Image
                  className="action_icon"
                  src={require("@/static/userInfo/order_btn.svg")}
                />
                <Text className="action_text">球局订单</Text>
              </View>
              <View className="action_divider"></View>
              <View className="action_content" onClick={handle_wallet}>
                <Image
                  className="action_icon"
                  src={require("@/static/userInfo/wallet.svg")}
                />
                <Text className="action_text">钱包</Text>
              </View>
            </View>
          </View>
        </View>

        <View className="test-entry-card-box">
          <NTRPTestEntryCard type={EvaluateScene.user} />
        </View>

        {/* 球局类型标签页 */}
        <View className="game_tabs_section">
          <View className="tab_container">
            <View
              className={`tab_item ${active_tab === "hosted" ? "active" : ""}`}
              onClick={() => setActiveTab("hosted")}
            >
              <Text className="tab_text">我主办的</Text>
            </View>
            <View
              className={`tab_item ${
                active_tab === "participated" ? "active" : ""
              }`}
              onClick={() => setActiveTab("participated")}
            >
              <Text className="tab_text">我参与的</Text>
            </View>
          </View>
        </View>

        {/* 球局列表 */}
        <View className="game_list_section">
          <ScrollView scrollY>
            <ListContainer
              data={game_records}
              recommendList={[]}
              loading={loading}
              error={null}
              errorImg="ICON_LIST_EMPTY"
              emptyText="暂未发布球局"
              btnText="去发布"
              btnImg="ICON_ADD"
              reload={goPublish}
              isShowNoData={game_records.length === 0}
              loadMoreMatches={() => {}}
              collapse={true}
              style={{ paddingBottom: 0, overflow: "hidden" }}
              defaultShowNum={3}
            />
          </ScrollView>
        </View>

        {/* 往期球局 */}
        <View className="ended_game_text">往期球局</View>
        <View className="game_list_section">
          {/* <View className="date_header">
            <Text className="date_text">5月29日</Text>
            <Text className="separator">/</Text>
            <Text className="weekday_text">星期六</Text>
          </View> */}

          {/* 球局列表 */}
          {/* <View className="game_list_section"> */}
          <ScrollView scrollY>
            <ListContainer
              data={ended_game_records}
              recommendList={[]}
              loading={loading}
              error={null}
              errorImg="ICON_LIST_EMPTY"
              isShowNoData={ended_game_records.length === 0}
              loadMoreMatches={() => {}}
              collapse={true}
              style={{ paddingBottom: "90px", overflow: "hidden" }}
              defaultShowNum={3}
            />
          </ScrollView>
          {/* </View> */}

          {/* 球局卡片 */}
          {/* <View className="game_cards">
            {game_records.map((game) => (
              <GameCard
                key={game.id}
                game={game}
                on_click={handle_game_detail}
              />
            ))}
          </View> */}
        </View>
      </View>
      <GuideBar currentPage="personal" />
    </View>
  );
};

export default withAuth(MyselfPage);
