import {
  Cell,
  Form,
  Input,
  NavBar,
  Popup,
  Button,
} from "@nutui/nutui-react-taro";
import { View } from "@tarojs/components";
import { ArrowLeft, ArrowRight } from "@nutui/icons-react-taro";
import { getStorageSync, navigateBack, showToast } from "@tarojs/taro";
import {
  changePasswordApi,
  sendChangePasswordCodeApi,
} from "../../../api/auth";
import "./index.scss";
import { useEffect, useState } from "react";

export default function Setting() {
  const [showBottom, setShowBottom] = useState(false);
  const [form] = Form.useForm();
  const [formData, setFormData] = useState({
    user_name: "",
    user_pwd: "",
    phone: "",
    code: "",
  });
  const [countdown, setCountdown] = useState(0);

  // 获取验证码
  const handleGetCode = async () => {
    if (countdown > 0) return;

    if (!formData.phone) {
      showToast({
        icon: "none",
        title: "请输入手机号码",
        duration: 2000,
      });
      return;
    }

    // 校验手机号格式
    const phoneRegex = /^1[3-9]\d{9}$/;
    if (!phoneRegex.test(formData.phone)) {
      showToast({
        icon: "none",
        title: "请输入正确的手机号",
      });
      return;
    }
    try {
      // 调用发送验证码接口
      await sendChangePasswordCodeApi({
        phone: formData.phone,
      });

      // 这里可以调用发送验证码的API
      showToast({
        title: "验证码已发送",
        duration: 2000,
        icon: "none",
      });
      setCountdown(60);
    } catch (error: any) {
      showToast({
        title: error.message,
        duration: 2000,
        icon: "none",
      });
    }
  };

  const handleSubmit = async (data: any) => {
    await changePasswordApi({
      user_name: data.user_name,
      user_pwd: data.user_pwd,
      phone: data.phone,
      code: data.code.detail.value,
    });
    showToast({
      title: "修改密码成功",
      duration: 2000,
      icon: "none",
    });
    setShowBottom(false);
  };

  useEffect(() => {
    let info = getStorageSync("vipInfo");
    setFormData({
      user_name: info.user_name,
      phone: info.phone,
      code: "",
      user_pwd: "",
    });
    form.setFieldValue("user_name", info.user_name);
    form.setFieldValue("phone", info.phone);
  }, []);

  return (
    <View>
      <NavBar
        back={
          <>
            <ArrowLeft />
            返回
          </>
        }
        fixed
        onBackClick={(e) => {
          e.preventDefault();
          navigateBack({ delta: 1 });
        }}
      >
        设置
      </NavBar>
      <Cell.Group className="pt-[40px]">
        <Cell
          className="nutui-cell-clickable"
          title="修改密码"
          align="center"
          extra={<ArrowRight />}
          onClick={() => {
            setShowBottom(true);
          }}
        />
      </Cell.Group>
      <Popup
        visible={showBottom}
        position="bottom"
        onClose={() => {
          setShowBottom(false);
        }}
      >
        <View>
          <Form form={form} onFinish={(data) => handleSubmit(data)}>
            <Form.Item label="账号" name="user_name">
              <Input
                placeholder="请输入账号"
                readOnly={true}
                value={formData.user_name}
                onChange={(value) =>
                  setFormData({ ...formData, user_name: value })
                }
              />
            </Form.Item>
            <Form.Item label="新密码" name="user_pwd">
              <Input
                placeholder="请输入新密码"
                value={formData.user_pwd}
                onChange={(value) =>
                  setFormData({ ...formData, user_pwd: value })
                }
              />
            </Form.Item>
            <Form.Item label="手机号码" name="phone">
              <Input
                placeholder="请输入手机号码"
                readOnly={true}
                value={formData.phone}
                onChange={(value) => setFormData({ ...formData, phone: value })}
              />
            </Form.Item>
            <Form.Item label="验证码" name="code">
              <View className="flex items-center">
                <Input
                  placeholder="请输入验证码"
                  value={formData.code}
                  onChange={(value) =>
                    setFormData({ ...formData, code: value })
                  }
                />
                <Button
                  className="w-[100px] h-[40px] text-[14px] text-[#333]"
                  disabled={countdown > 0}
                  onClick={handleGetCode}
                  size="small"
                  type="primary"
                >
                  {countdown > 0 ? `${countdown}s` : "获取验证码"}
                </Button>
              </View>
            </Form.Item>
            <Form.Item>
              <Button
                block
                type="primary"
                size="large"
                onClick={() => form.submit}
              >
                提交
              </Button>
            </Form.Item>
          </Form>
        </View>
      </Popup>
    </View>
  );
}
