import "./index1.scss";
import { useState } from "react";
import {
  showModal,
  showToast,
  navigateTo,
  setStorageSync,
  redirectTo,
} from "@tarojs/taro";
import { sendCodeApi, smsLoginApi } from "../../api/auth";
const LoginIndex = () => {
  const [countdown, setCountdown] = useState(0);
  const [formData, setFormData] = useState({
    phone: "",
    code: "",
  });
  const handleInputChange = (e: any) => {
    setFormData({ ...formData, [e.target.name]: e.target.value });
  };
  // 处理登录
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    // 表单验证
    if (!formData.phone || !formData.code) {
      showModal({
        content: "请填写完整信息",
      });
      return;
    }

    const phoneRegex = /^1[3-9]\d{9}$/;
    if (!phoneRegex.test(formData.phone)) {
      showModal({
        content: "请输入正确的手机号",
      });
      return;
    }

    if (formData.code.length !== 4) {
      showModal({
        content: "验证码长度应为4位",
      });
      return;
    }

    try {
      const res: any = await smsLoginApi({
        mobile: formData.phone,
        code: formData.code,
      });

      const { data } = res;
      const {
        token,
        username,
        mobile,
        is_vip,
        vip_code,
        circle_info,
        vip_info,
      } = data;
      setStorageSync("Authorization", token);
      setStorageSync("User", { username, mobile, is_vip, vip_code });
      setStorageSync("vipInfo", vip_info);
      setStorageSync("circleInfo", circle_info);
      redirectTo({ url: "/pages/index/index" });

      showToast({
        title: "登录成功",
        icon: "none",
        duration: 2000,
      });

      navigateTo({ url: "/pages/index/index" });
    } catch (error) {
      showToast({
        title: "登录失败，请重试",
        icon: "none",
        duration: 2000,
      });
    }
  };

  // 发送验证码
  const handleSendCode = async () => {
    try {
      if (!formData.phone) {
        showModal({
          content: "请先输入手机号",
          showCancel: false,
          confirmColor: "#4d7ced",
        });
        return;
      }

      const phoneRegex = /^1[3-9]\d{9}$/;
      if (!phoneRegex.test(formData.phone)) {
        showModal({
          content: "请输入正确的手机号",
          showCancel: false,
          confirmColor: "#4d7ced",
        });
        return;
      }

      await sendCodeApi({ mobile: formData.phone });
      showToast({
        title: "验证码已发送",
        icon: "none",
        duration: 2000,
      });
      setCountdown(60);
      const timer = setInterval(() => {
        setCountdown((prev) => {
          if (prev <= 1) {
            clearInterval(timer);
            return 0;
          }
          return prev - 1;
        });
      }, 1000);
    } catch (error: any) {
      showToast({
        title: error.msg || "发送失败，请重试",
        icon: "none",
        duration: 2000,
      });
    }
  };

  return (
    <div className="login-page">
      <div className="login-container">
        <div className="login-header">
          <h1>Hello!</h1>
          <p>很高兴见到您，欢迎来到玩家中心</p>
        </div>

        <div className="login-card">
          <h2>短信登录</h2>
          <form onSubmit={handleSubmit} className="login-form">
            <div className="form-item">
              <div className="label">账号</div>
              <div className="input-container">
                <i className="phone-icon"></i>
                <input
                  type="tel"
                  name="phone"
                  className="custom-input"
                  placeholder="请输入手机号"
                  value={formData.phone}
                  onChange={handleInputChange}
                  maxLength={11}
                />
              </div>
            </div>

            <div className="form-item">
              <div className="label">验证码</div>
              <div className="code-container">
                <div className="input-container">
                  <i className="shield-icon"></i>
                  <input
                    type="text"
                    name="code"
                    className="custom-input"
                    placeholder="输入验证码"
                    value={formData.code}
                    onChange={handleInputChange}
                    maxLength={6}
                  />
                </div>
                <button
                  type="button"
                  className="code-btn"
                  disabled={countdown > 0}
                  onClick={handleSendCode}
                >
                  {countdown > 0 ? `${countdown}s` : "获取验证码"}
                </button>
              </div>
            </div>

            <button type="submit" className="submit-btn">
              登录
            </button>
          </form>
        </div>
      </div>
    </div>
  );
};

export default LoginIndex;
