"use client";

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

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

  //保存区号
  const [regionCode, setRegionCode] = useState("86");

  //设置checkbox
  const [checked, setChecked] = useState(false);

  //点击登录
  const handleSubmit = async (value) => {
    if (!checked) {
      Toast.show({
        content: "请先勾选同意《用户协议》和《隐私政策》后登录",
      });
      return;
    }
    if (!value.mobile_phone || !value.password) {
      Toast.show({
        content: "请完善信息",
      });
      return;
    }
    if (!value.mobile_phone.match(/^1[3456789]\d{9}$/)) {
      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加密password
    const encryptedPassword = cryptoPassword(value.password);
    //发送登录请求
    try {
      const base = baseRequest();
      const signature = generateSignature({
        mobile_phone: mobile_phone,
        region_code: regionCode,
        password: encryptedPassword,
        ...base,
      });
      const response = await fetch(
        `/api/login/login_by_pswd?signature=${signature}`,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            mobile_phone: mobile_phone,
            region_code: regionCode,
            password: encryptedPassword,
            ...base,
          }),
        }
      );
      const data = await response.json();
      if (data.ret === -1) {
        Toast.show({
          content: data.msg,
        });
        return;
      }
      signIn(data);
      router.back();
    } catch (error) {
      console.error(error);
    }
  };

  return (
    <section className="flex flex-1 flex-col">
      <div className="flex flex-1 flex-row justify-center">
        <Form
          style={{
            "--border-top": "0",
            "--border-bottom": "0",
            "--border-inner": "0",
          }}
          layout="horizontal"
          onFinish={handleSubmit}
        >
          <div className="w-96 p-4 bg-[#07050A]">
            <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 whitespace-nowrap">
                    +{regionCode}
                  </p>
                  <Input placeholder="请输入手机号" type="number" 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>
            </div>
            <div className="flex justify-end mt-4 mb-8">
              <Link className="text-primary" href="../resetpassword">
                忘记密码？
              </Link>
            </div>
            <div className="flex justify-center mt-8 mb-4">
              <Checkbox
                style={{
                  "--icon-size": "18px",
                  "--font-size": "14px",
                  "--gap": "6px",
                }}
                checked={checked}
                onChange={() => setChecked(!checked)}
              >
                <p className="text-gray-400 text-sm">
                  同意
                  <Link className="link text-primary" href="/doc/useragreement">
                    《用户协议》
                  </Link>
                  、
                  <Link className="link text-primary" href="/doc/privatypolicy">
                    《隐私政策》
                  </Link>
                </p>
              </Checkbox>
            </div>
            <div className="flex justify-center">
              <button
                type="submit"
                className="btn btn-primary w-full text-base text-white font-medium"
              >
                登录
              </button>
            </div>
          </div>
        </Form>
      </div>
    </section>
  );
}
