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

const MyselfPageContent: React.FC = () => {
  const pickerOption = usePickerOption();
  const { statusNavbarHeightInfo } = useGlobalState() || {};
  const { totalHeight = 98 } = statusNavbarHeightInfo || {};
  
  const instance = (Taro as any).getCurrentInstance();
  const user_id = instance.router?.params?.userid || "";
  const is_current_user = !user_id;
  const user_info = useUserInfo();

  const [game_records, set_game_records] = useState<TennisMatch[]>([]);
  const [ended_game_records, setEndedGameRecords] = useState<TennisMatch[]>([]);
  const [loading] = useState(false);
  const [is_following, setIsFollowing] = useState(false);
  const [active_tab, setActiveTab] = useState<"hosted" | "participated">("hosted");

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

  const { useDidShow } = Taro as any;
  useDidShow(() => {
    // 确保从编辑页面返回时刷新数据
  });

  useEffect(() => {
    if (!loading) {
      load_game_data();
    }
  }, [active_tab]);

  const classifyGameRecords = (
    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[],
      }
    );
  };

  const load_game_data = async () => {
    try {
      if (!user_info || !('id' in user_info)) {
        return;
      }
      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);
    } catch (error) {
      console.error("加载球局数据失败:", error);
    }
  };

  const handle_follow = async () => {
    try {
      const new_following_state = await UserService.toggle_follow(
        user_id,
        is_following
      );
      setIsFollowing(new_following_state);

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

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

  const handle_game_orders = () => {
    (Taro as any).navigateTo({
      url: "/order_pages/orderList/index",
    });
  };

  const handle_wallet = () => {
    (Taro as any).navigateTo({
      url: "/user_pages/wallet/index",
    });
  };

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

  return (
    <View className="myself_page">
      <View className="myself_page_content_main" style={{ paddingTop: `${totalHeight}px` }}>
        <View className="user_info_section">
          <UserInfoCard
            editable={is_current_user}
            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">
          <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>
    </View>
  );
};

export default MyselfPageContent;

