import React, { useState, useEffect } from "react";
import { View, Text, ScrollView, Image } from "@tarojs/components";
import ListContainer from "@/container/listContainer";
import Taro from "@tarojs/taro";
import img from "@/config/images";
import "./index.scss";
// import GuideBar from "@/components/GuideBar";
import {
  UserInfoCard,
  // GameCard,
  GameTabs,
  UserInfo,
  GameRecord,
} from "@/components/UserInfo";
import { UserService } from "@/services/userService";
import * as LoginService from "@/services/loginService";

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

  // 模拟用户数据
  const [user_info, setUserInfo] = useState<UserInfo>({
    id: user_id || "1",
    gender: "",
    nickname: "网球爱好者",
    avatar: require("@/static/userInfo/default_avatar.svg"),
    join_date: "2024年3月加入",
    stats: {
      following: 0,
      friends: 0,
      hosted: 0,
      participated: 0,
    },
    tags: ["北京朝阳", "金融从业者", "NTRP 3.5"],
    bio: "热爱网球的金融从业者，周末喜欢约球\n技术还在提升中，欢迎一起切磋\n平时在朝阳公园附近活动",
    location: "北京朝阳",
    occupation: "金融从业者",
    ntrp_level: "NTRP 3.5",
    is_following: false,
    ongoing_games: [],
    personal_profile: "",
  });

  // 模拟球局数据
  const [game_records, setGameRecords] = useState<GameRecord[]>([]);
  // 往期球局
  const [ended_game_records, setEndedGameRecords] = useState<GameRecord[]>([]);

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

  const [loading, set_loading] = useState(true);

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

  // 页面加载时获取用户信息
  useEffect(() => {
    const load_user_data = async () => {
      if (user_id) {
        try {
          // const user_data = await UserService.get_user_info(user_id);
          const res = await LoginService.getUserInfoById(user_id);
          const { data: userData } = res;
          // setUserInfo({...res.data as UserInfo, avatar: data.avatar_url || require("@/static/userInfo/default_avatar.svg")});
          setUserInfo({
            id: user_id || "",
            nickname: userData.nickname || "",
            avatar: userData.avatar_url || "",
            join_date: userData.subscribe_time
              ? `${new Date(userData.subscribe_time).getFullYear()}年${
                  new Date(userData.subscribe_time).getMonth() + 1
                }月加入`
              : "",
            stats: {
              following: userData.stats?.following_count || 0,
              friends: userData.stats?.followers_count || 0,
              hosted: userData.stats?.hosted_games_count || 0,
              participated: userData.stats?.participated_games_count || 0,
            },

            personal_profile: userData.personal_profile || "",
            location: userData.city + userData.district || "",
            occupation: userData.occupation || "",
            ntrp_level: "",
            phone: userData.phone || "",
            gender: userData.gender || "",
            birthday: userData.birthday || "",
          });
          setIsFollowing(userData.is_following || false);
        } catch (error) {
          console.error("加载用户数据失败:", error);
          Taro.showToast({
            title: "加载失败",
            icon: "none",
          });
        }
      }
    };

    load_user_data();
  }, [user_id]);

  const classifyGameRecords = (
    game_records: GameRecord[]
  ): { notEndGames: GameRecord[]; finishedGames: GameRecord[] } => {
    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 GameRecord[],
        finishedGames: [] as GameRecord[],
      }
    );
  };

  const load_game_data = async () => {
    try {
      set_loading(true);
      const games_data = await UserService.get_user_games(
        user_id || "",
        active_tab
      );
      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);
      setGameRecords(notEndGames);
      setEndedGameRecords(finishedGames);
    } catch (error) {
      console.error("加载球局数据失败:", error);
      Taro.showToast({
        title: "加载失败，请重试",
        icon: "error",
        duration: 2000,
      });
    } finally {
      set_loading(false);
    }
  };

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

  // 处理关注/取消关注
  const handle_follow = async () => {
    try {
      const new_follow_status = await UserService.toggle_follow(
        user_info.id,
        is_following
      );
      setIsFollowing(new_follow_status);
      Taro.showToast({
        title: new_follow_status ? "关注成功" : "已取消关注",
        icon: "success",
        duration: 1500,
      });
    } catch (error) {
      console.error("关注操作失败:", error);
      Taro.showToast({
        title: "操作失败",
        icon: "none",
      });
    }
  };

  // 处理发送消息
  const handle_send_message = () => {
    Taro.navigateTo({
      url: `/mode_user/message/chat/index?user_id=${user_info.id}&nickname=${user_info.nickname}`,
    });
  };

  // 处理球局详情
  // const handle_game_detail = (game_id: string) => {
  //   Taro.navigateTo({
  //     url: `/game_pages/detail/index?id=${game_id}&from=personal`,
  //   });
  // };

  return (
    <View className="other_user_page">
      <View className="custom-navbar">
        <View className="detail-navigator">
          <View
            className="detail-navigator-back"
            onClick={() => {
              Taro.navigateBack();
            }}
          >
            <Image
              className="detail-navigator-back-icon"
              src={img.ICON_NAVIGATOR_BACK}
            />
          </View>
        </View>
      </View>
      {/* 主要内容 */}
      <View className="main_content">
        {/* 用户信息区域 */}
        <View className="user_info_section">
          <UserInfoCard
            user_info={user_info}
            is_current_user={false}
            is_following={is_following}
            on_follow={handle_follow}
            on_message={handle_send_message}
          />
        </View>

        {/* 球局类型标签页 */}
        <GameTabs
          active_tab={active_tab}
          on_tab_change={setActiveTab}
          is_current_user={false}
        />

        {/* 球局列表 */}
        <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={game_records}
                recommendList={[]}
                loading={loading}
                error={null}
                reload={load_game_data}
                loadMoreMatches={() => {}}
              />
            </ScrollView>
          {/* </View> */}

          {/* 球局卡片 */}
          {/* <View className="game_cards">
            {game_records.map((game) => (
              <GameCard
                key={game.id}
                game={game}
                on_click={handle_game_detail}
              />
            ))}
          </View> */}
        </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}
                reload={load_game_data}
                loadMoreMatches={() => {}}
              />
            </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 OtherUserPage;
