import React, { useState } from "react";
import { View, Text, Button, Image } from "@tarojs/components";
import Taro, { useRouter } from "@tarojs/taro";
import { GeneralNavbar } from "@/components";
import {
  wechat_auth_login,
  save_login_state,
  check_login_status,
} from "@/services/loginService";
import { useUserActions } from "@/store/userStore";
import "./index.scss";

const LoginPage: React.FC = () => {
  const [is_loading, set_is_loading] = useState(false);
  const [agree_terms, set_agree_terms] = useState(false);
  const [show_terms_layer, set_show_terms_layer] = useState(false);
  const [pending_login_type, set_pending_login_type] = useState<
    "wechat" | "phone" | null
  >(null); // 记录待执行的登录类型
  const [pending_phone_event, set_pending_phone_event] = useState<any>(null); // 记录微信登录的事件数据
  const {
    params: { redirect },
  } = useRouter();
  const { fetchUserInfo, checkNicknameChangeStatus } = useUserActions();

  // 执行微信登录的核心逻辑
  const execute_wechat_login = async (e: any) => {
    // 检查是否获取到手机号
    if (!e.detail || !e.detail.code) {
      Taro.showToast({
        title: "获取手机号失败，请重试",
        icon: "none",
        duration: 2000,
      });
      return;
    }

    set_is_loading(true);
    try {
      // 传递手机号code给登录服务
      const response = await wechat_auth_login(e.detail.code);
      if (response.success) {
        save_login_state(response.token!, response.user_info!);
        fetchUserInfo();
        checkNicknameChangeStatus();

        setTimeout(() => {
          if (redirect) {
            Taro.redirectTo({ url: decodeURIComponent(redirect) });
          } else {
            Taro.redirectTo({ url: "/main_pages/index" });
          }
        }, 10);
      } else {
        Taro.showToast({
          title: response.message,
          icon: "none",
          duration: 2000,
        });
      }
    } catch (error) {
      Taro.showToast({
        title: "登录失败，请重试",
        icon: "none",
        duration: 2000,
      });
    } finally {
      set_is_loading(false);
    }
  };

  // 微信授权登录
  const handle_wechat_login = async (e: any) => {
    if (!agree_terms) {
      // 记录待执行的登录类型和事件数据
      set_pending_login_type("wechat");
      set_pending_phone_event(e);
      set_show_terms_layer(true);
      Taro.showToast({
        title: "请先同意用户协议",
        icon: "none",
        duration: 2000,
      });
      return;
    }

    // 如果已同意条款，直接执行登录
    await execute_wechat_login(e);
  };

  // 执行手机号登录的核心逻辑
  const execute_phone_login = () => {
    // 跳转到验证码页面
    Taro.navigateTo({
      url: `/login_pages/verification/index?redirect=${redirect}`,
    });
  };

  // 手机号验证码登录
  const handle_phone_login = async () => {
    if (!agree_terms) {
      // 记录待执行的登录类型
      set_pending_login_type("phone");
      set_show_terms_layer(true);
      Taro.showToast({
        title: "请先同意用户协议",
        icon: "none",
        duration: 2000,
      });
      return;
    }

    // 如果已同意条款，直接执行登录
    execute_phone_login();
  };

  // 同意协议并关闭浮层，继续执行未完成的登录
  const handle_agree_terms = () => {
    set_agree_terms(true);
    set_show_terms_layer(false);

    // 根据待执行的登录类型，继续执行登录
    if (pending_login_type === "wechat" && pending_phone_event) {
      // 继续执行微信登录
      execute_wechat_login(pending_phone_event);
      // 清空待执行状态
      set_pending_login_type(null);
      set_pending_phone_event(null);
    } else if (pending_login_type === "phone") {
      // 继续执行手机号登录
      execute_phone_login();
      // 清空待执行状态
      set_pending_login_type(null);
    }
  };

  // 切换协议同意状态（复选框用）
  const handle_toggle_terms = () => {
    set_agree_terms(!agree_terms);
  };

  // 查看协议
  const handle_view_terms = (type: string = "terms") => {
    Taro.navigateTo({
      url: `/login_pages/terms/index?type=${type}`,
    });
  };

  // 点击浮层外部关闭浮层
  const handle_overlay_click = () => {
    set_show_terms_layer(false);
  };

  // 点击浮层内部阻止事件冒泡
  const handle_layer_click = (e: any) => {
    e.stopPropagation();
  };

  // 返回首页
  const handle_return_home = () => {
    Taro.navigateTo({ url: "/main_pages/index" });
  };

  return (
    <View className="login_page">
      <View className="background_image">
        <Image
          className="bg_img"
          src={require("@/static/login/login_bg.jpg")}
          mode="aspectFill"
        />
        <View className="bg_overlay"></View>
      </View>

      <GeneralNavbar title="" showBack={true} showAvatar={false} onBack={handle_return_home} />

      {/* 主要内容 */}
      <View className="login_main_content">
        {/* 品牌区域 */}
        <View className="brand_section">
          <View className="logo_container"></View>

          <View className="slogan_container"></View>
        </View>

        {/* 登录按钮区域 */}
        <View className="login_section">
          {/* 微信快捷登录 */}
          <Button
            className={`login_button wechat_button ${
              is_loading ? "loading" : ""
            }`}
            openType="getPhoneNumber"
            onGetPhoneNumber={handle_wechat_login}
            disabled={is_loading}
          >
            <View className="wechat_icon">
              <Image
                className="wechat_logo"
                src={require("@/static/login/wechat_icon.svg")}
              />
            </View>
            <Text className="button_text">
              {is_loading ? "登录中..." : "一键登录"}
            </Text>
          </Button>

          {/* 手机号验证码登录 */}
          <Button
            className="login_button phone_button"
            onClick={handle_phone_login}
          >
            <View className="phone_icon">
              <Image
                className="phone_logo"
                src={require("@/static/login/phone_icon.svg")}
              />
            </View>
            <Text className="button_text">手机号快捷登录</Text>
          </Button>

          {/* <View className="return_home_button link_button" onClick={handle_return_home}>
            <Text className="button_text">返回首页</Text>
          </View> */}

          {/* 用户协议复选框 */}
          <View className="terms_checkbox_section">
            <View className="checkbox_container" onClick={handle_toggle_terms}>
              <View className={`checkbox ${agree_terms ? "checked" : ""}`}>
                {/* {agree_terms && <View className="checkmark"></View>} */}
              </View>
            </View>
            <View className="terms_text_container">
              <Text className="terms_text">我已阅读、理解并接受以下规定</Text>
              <Text
                className="terms_link"
                onClick={() => handle_view_terms("terms")}
              >
                《有场的条款和条件》
              </Text>
              <Text
                className="terms_link"
                onClick={() => handle_view_terms("binding")}
              >
                《有场与微信号绑定协议》
              </Text>
              <Text
                className="terms_link"
                onClick={() => handle_view_terms("privacy")}
              >
                《隐私权政策》
              </Text>
            </View>
          </View>
        </View>
      </View>

      {/* 底部条款浮层遮罩 */}
      {show_terms_layer && (
        <View className="terms_overlay" onClick={handle_overlay_click}>
          {/* 底部条款浮层 */}
          <View className="terms_float_layer" onClick={handle_layer_click}>
            {/* 浮层标题 */}
            <View className="float_title">
              <Text className="title_text">请阅读并同意以下条款</Text>
            </View>

            {/* 条款列表 */}
            <View className="terms_list">
              <Text
                className="terms_item"
                onClick={() => handle_view_terms("terms")}
              >
                《有场的条款和条件》
              </Text>
              <Text
                className="terms_item"
                onClick={() => handle_view_terms("binding")}
              >
                《有场与微信号绑定协议》
              </Text>
              <Text
                className="terms_item"
                onClick={() => handle_view_terms("privacy")}
              >
                《隐私权政策》
              </Text>
            </View>

            {/* 同意按钮 */}
            <Button
              className={`agree_button ${agree_terms ? "agreed" : ""}`}
              onClick={handle_agree_terms}
            >
              {agree_terms ? "已同意" : "同意并继续"}
            </Button>
          </View>
        </View>
      )}
    </View>
  );
};

export default LoginPage;
