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

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

interface FormFields {
  new_password: string;
  confirm_password: string;
  sms_code?: string;
}

const SetTransactionPassword: 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("获取验证码");
  const [valid, setValid] = useState(false);
  // 使用全局键盘状态监听
  useEffect(() => {
    // 初始化全局键盘监听器
    initializeKeyboardListener();

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

    return () => {
      removeListener();
    };
  }, [initializeKeyboardListener, addListener]);
  const [handleType, setHandleType] = useState("set");
  const router = useRouter();
  const { type } = router.params;

  useEffect(() => {
    if (type) {
      setHandleType(type);
    }
  }, [type]);

  const [formData, setFormData] = useState<FormFields>({
    new_password: "",
    confirm_password: "",
    sms_code: "",
  });

  useEffect(() => {
    const { new_password, confirm_password, sms_code } = formData;
    if (handleType === "set") {
      setValid(
        !!sms_code && new_password.length === 6 && confirm_password.length === 6
      );
    } else {
      setValid(new_password.length === 6 && confirm_password.length === 6);
    }
  }, [formData]);

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

  const handleConfirm = async () => {
    if (!valid) return;
    const { new_password, confirm_password } = formData;
    if (new_password !== confirm_password) {
      Taro.showToast({
        title: "两次密码输入不一致",
        icon: "none",
      });
      return;
    }
    try {
      await httpService.post("/wallet/set_payment_password", {
        password: new_password,
      });
      Taro.showToast({
        title: "设置交易密码成功",
        icon: "success",
      });
      Taro.redirectTo({
        url: "/user_pages/wallet/index",
      });
    } catch (error) {
      Taro.showToast({
        title: "设置交易密码失败",
        icon: "none",
      });
      return;
    }
  };

  const getSMSCode = async () => {
    try {
      await httpService.post("/wallet/send_set_password_sms", {
        type: "set_password",
      });
      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) {
      Taro.showToast({
        title: "验证码发送失败",
        icon: "none",
      });
      return;
    }
  };

  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>
      <View className="form-item">
        <Text className="form-label">交易密码</Text>
        <Input
          placeholder="请输入交易密码"
          password
          type="number"
          maxlength={6}
          onInput={(e) => {
            handleInput(e, "new_password");
          }}
        ></Input>
      </View>
      <View className="form-item">
        <Text className="form-label">重复密码</Text>
        <Input
          placeholder="请再次输入交易密码"
          password
          type="number"
          maxlength={6}
          onInput={(e) => {
            handleInput(e, "confirm_password");
          }}
        ></Input>
      </View>
      {handleType === "set" && (
        <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>
      )}
      <Text className="tips">* 密码由6位数字组成</Text>
      <Button
        className={`btn bottom-btn ${!valid ? "disabled" : ""}`}
        onClick={handleConfirm}
        style={{
          bottom: isKeyboardVisible ? `${keyboardHeight + 20}px` : undefined,
        }}
      >
        完成
      </Button>
    </View>
  );
};

export default SetTransactionPassword;
