"use client";

import React, { useState, useEffect } from "react";
import { Form, Input, Toast } from "antd-mobile";
import { JSEncrypt } from "jsencrypt";
import { cryptoPassword, generateSignature } from "@/utils/crypto";
import { useRouter } from "next/navigation";
import baseRequest from "@/utils/baseRequest";

export default function ResetPassword() {
  const router = useRouter();

  //保存区号、手机号、验证码
  const [regionCode, setRegionCode] = useState("86");
  const [mobilePhone, setMobilePhone] = useState("");

  //重新获取验证码的计时器
  const [isCounting, setIsCounting] = useState(false);
  const [seconds, setSeconds] = useState(60);
  useEffect(() => {
    let interval;
    if (isCounting && seconds > 0) {
      interval = setInterval(() => {
        setSeconds(seconds - 1);
      }, 1000);
    } else {
      setIsCounting(false);
      setSeconds(60);
      clearInterval(interval);
    }
    return () => {
      clearInterval(interval);
    };
  }, [isCounting, seconds]);

  //点击获取验证码
  const handleVerification = async () => {
    //手机号校验
    if (!mobilePhone.match(/^1[3456789]\d{9}$/)) {
      Toast.show({
        content: "手机号码格式错误",
      });
      return;
    }
    //开始倒计时
    setIsCounting(true);
    //对手机号进行RSA加密
    const encrypt = new JSEncrypt();
    encrypt.setPublicKey(process.env.NEXT_PUBLIC_RSA_KEY);
    const mobile_phone = encrypt.encrypt(mobilePhone);
    const base = baseRequest();
    const signature = generateSignature({
      mobile_phone: mobile_phone,
      region_code: regionCode,
      ...base,
    });
    //发送短信验证码
    try {
      await fetch(`/api/veri_code/send?signature=${signature}`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          mobile_phone: mobile_phone,
          region_code: regionCode,
          ...base,
        }),
      });
    } catch (error) {
      console.error(error);
    }
  };

  //点击登录
  const handleSubmit = async (value) => {
    if (!value.mobile_phone) {
      Toast.show({
        content: "请输入手机号码",
      });
      return;
    }
    if (!value.mobile_phone.match(/^1[3456789]\d{9}$/)) {
      Toast.show({
        content: "手机号码格式错误",
      });
      return;
    }
    if (!value.veri_code) {
      Toast.show({
        content: "请先输入正确的验证码",
      });
      return;
    }
    if (!value.password) {
      Toast.show({
        content: "请输入您的密码",
      });
      return;
    }
    if (!value.confirm_password) {
      Toast.show({
        content: "请再次输入您的密码",
      });
      return;
    }
    if (value.password != value.confirm_password) {
      Toast.show({
        content: "两次输入密码不一致",
      });
      return;
    }
    if (value.password.length < 8) {
      Toast.show({
        content: "新密码不得小于8位",
      });
      return;
    }
    if (value.password.length > 15) {
      Toast.show({
        content: "新密码不得大于15位",
      });
      return;
    }

    //对手机号进行RSA加密
    const encrypt = new JSEncrypt();
    encrypt.setPublicKey(process.env.NEXT_PUBLIC_RSA_KEY);
    const mobile_phone = encrypt.encrypt(value.mobile_phone);
    //MD5加密新旧密码
    const encryptedPassword = cryptoPassword(value.password);
    //发送修改密码请求
    const base = baseRequest();
    const signature = generateSignature({
      mobile_phone: mobile_phone,
      region_code: regionCode,
      veri_code: value.veri_code,
      new_password: encryptedPassword,
      ...base,
    });
    try {
      const response = await fetch(
        `/api/login/reset_password?signature=${signature}`,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            mobile_phone: mobile_phone,
            region_code: regionCode,
            veri_code: value.veri_code,
            new_password: encryptedPassword,
            ...base,
          }),
        }
      );
      const data = await response.json();
      if (data.ret === -1) {
        Toast.show({
          content: data.msg,
        });
        return;
      }
      router.back();
    } catch (error) {
      console.error(error);
    }
  };

  return (
    <section className="flex flex-1 flex-col">
      <div className="flex flex-row justify-center mt-24">
        <Form
          style={{
            "--border-top": "0",
            "--border-bottom": "0",
            "--border-inner": "0",
          }}
          layout="horizontal"
          onFinish={handleSubmit}
        >
          <div className="w-96 p-4 bg-[#07050A]">
            <h1 className="text-3xl font-semibold">重置密码</h1>
            <p className="text-base text-secondary mb-10">请牢记密码</p>
            <div className="rounded-2xl overflow-hidden border-neutral border">
              <Form.Item name="mobile_phone">
                <div className="flex flex-row">
                  <p className="mr-4 text-white">+{regionCode}</p>
                  <Input
                    placeholder="请输入手机号"
                    clearable
                    value={mobilePhone}
                    onChange={(value) => setMobilePhone(value)}
                  />
                </div>
              </Form.Item>
              <hr className="mx-4 border-neutral" />
              <Form.Item
                name="veri_code"
                extra={
                  <button disabled={isCounting} onClick={handleVerification}>
                    <p className={isCounting ? "" : "text-primary"}>
                      {isCounting ? `(${seconds})重新发送` : "获取验证码"}
                    </p>
                  </button>
                }
              >
                <div className="flex flex-row">
                  <p className="mr-4 text-white whitespace-nowrap">验证码</p>
                  <Input placeholder="请输入验证码" clearable />
                </div>
              </Form.Item>
              <hr className="mx-4 border-neutral" />
              <Form.Item name="password">
                <div className="flex flex-row">
                  <p className="mr-4 text-white whitespace-nowrap">新密码</p>
                  <Input placeholder="请输入新密码" type="password" clearable />
                </div>
              </Form.Item>
              <hr className="mx-4 border-neutral" />
              <Form.Item name="confirm_password">
                <div className="flex flex-row">
                  <p className="mr-4 text-white whitespace-nowrap">确认密码</p>
                  <Input
                    placeholder="请再次输入新密码"
                    type="password"
                    clearable
                  />
                </div>
              </Form.Item>
            </div>
            <div className="flex justify-center mt-12">
              <button
                type="submit"
                className="btn btn-primary w-full text-base text-white font-medium"
              >
                确认重置
              </button>
            </div>
          </div>
        </Form>
      </div>
    </section>
  );
}