import React, { useState, useEffect } from "react";
import Taro from "@tarojs/taro";
import { View, Text, Input, Button, Image } from "@tarojs/components";

import "./index.scss";
import httpService from "@/services/httpService";
import { useUserInfo } from "@/store/userStore";
import { useKeyboardHeight } from "@/store/keyboardStore";
import img from "@/config/images";
import { BackNavbar } from "@/components";

interface FormFields {
  phone?: string;
  sms_code?: string;
}

const ValidPhone: React.FC = () => {
  // 获取当前页面的配置
  const currentPage = Taro.getCurrentInstance();
  const pageConfig = currentPage.page?.config;
  const pageTitle = pageConfig?.navigationBarTitleText;
  // 使用全局键盘状态
  const {
    keyboardHeight,
    isKeyboardVisible,
    addListener,
    initializeKeyboardListener,
  } = useKeyboardHeight();
  const [smsCodeSended, setSmsCodeSended] = useState(false);
  const [smsCodeText, setSmsCodeText] = useState("获取验证码");
  // 使用全局键盘状态监听
  useEffect(() => {
    // 初始化全局键盘监听器
    initializeKeyboardListener();

    // 添加本地监听器
    const removeListener = addListener((height, visible) => {
      console.log("AiImportPopup 收到键盘变化:", height, visible);
    });

    return () => {
      removeListener();
    };
  }, [initializeKeyboardListener, addListener]);
  const userInfo = useUserInfo();
  const [formData, setFormData] = useState<FormFields>({
    phone: userInfo.phone || "",
    sms_code: "",
  });

  const handleInput = (e: any, field: string) => {
    setFormData({ ...formData, [field]: e.detail.value });
  };

  const handleConfirm = async () => {
    const isValid = await validSMSCode();
    if (isValid) {
      Taro.navigateTo({
        url: `/user_pages/setTransactionPassword/index?type=reset&phone=${formData.phone}&sms_code=${formData.sms_code}`,
      });
    }
  };

  const validSMSCode = async () => {
    const { phone, sms_code } = formData;
    try {
      const res = await httpService.post("/wallet/verify_sms_code", {
        phone,
        sms_code,
        type: "reset_password",
      });
      const { verified } = res.data;
      if (verified) {
        return true;
      } else {
        Taro.showToast({ title: "验证码校验失败", icon: "none" });
        return false;
      }
    } catch (error) {
      console.log(error);
      Taro.showToast({ title: "验证码校验失败", icon: "none" });
      return false;
    }
  };

  const getSMSCode = async () => {
    const { phone } = formData;
    try {
      await httpService.post("/wallet/send_reset_password_sms", { phone });
      Taro.showToast({ title: "验证码已发送", icon: "none" });
      let time = 60;
      setSmsCodeText(`${time}秒后重发`);
      const timer = setInterval(() => {
        if (time > 0) {
          time--;
          setSmsCodeText(`${time}秒后重发`);
        } else {
          setSmsCodeText("获取验证码");
          setSmsCodeSended(false);
          clearInterval(timer);
        }
      }, 1000);
      setSmsCodeSended(true);
    } catch (error) {
      console.log(error);
      Taro.showToast({ title: "获取验证码失败", icon: "none" });
    }
  };

  return (
    <View className="set-transaction-password-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}
            />
            <Text>{pageTitle}</Text>
          </View>
        </View>
      </View> */}
      {/* 顶部导航栏 */}
      <BackNavbar
        title={pageTitle}
        showBackButton={true}
        showAvatar={false}
        onBack={() => {
          Taro.navigateBack();
        }}
      />
      <View className="form-item">
        <Text className="form-label">手机号</Text>
        <Input defaultValue={formData.phone} type="number" disabled></Input>
      </View>
      <View className="form-item">
        <Text className="form-label">验证码</Text>
        <Input
          placeholder="请输入验证码"
          type="number"
          onInput={(e) => {
            handleInput(e, "sms_code");
          }}
        ></Input>
        <Button
          className={`btn ${smsCodeSended ? "disabled" : ""}`}
          disabled={smsCodeSended}
          onClick={getSMSCode}
        >
          {smsCodeText}
        </Button>
      </View>
      <Button
        className={`btn bottom-btn ${
          formData.sms_code === "" ? "disabled" : ""
        }`}
        disabled={formData.sms_code === ""}
        onClick={handleConfirm}
        style={{
          bottom: isKeyboardVisible ? `${keyboardHeight + 20}px` : undefined,
        }}
      >
        提交
      </Button>
    </View>
  );
};

export default ValidPhone;
