"use client";
import React, { useState } from "react";
import { Toast } from "antd-mobile";
import { uploadImage } from "@/utils/upload";
import { getCookie } from "cookies-next";
import baseRequest from "@/utils/baseRequest";
import { JSEncrypt } from "jsencrypt";
import { useRouter } from "next/navigation";
import { generateSignature } from "@/utils/crypto";
import Image from "next/image";

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

  const [idNumber, setIdNumber] = useState("");
  const [realName, setRealName] = useState("");
  const [idCardFront, setIdCardFront] = useState();
  const [idCardBack, setIdCardBack] = useState();
  const [handleIdCard, setHandleIdCard] = useState();
  const [isSubmitting, setIsSubmitting] = useState(false);

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (
      !idNumber ||
      !realName ||
      !idCardFront ||
      !idCardBack ||
      !handleIdCard
    ) {
      Toast.show({ content: "请完善信息后提交" });
      return;
    }
    if (idNumber.length !== 18) {
      Toast.show({ content: "身份证位数不正确" });
      return;
    }
    const mid = getCookie("mid");
    const token = getCookie("token");
    if (!mid || !token) {
      Toast.show({ content: "身份验证失败，请联系客服提现" });
      return;
    }
    setIsSubmitting(true);
    const idCardFrontSrcId = await uploadImage(idCardFront);
    const idCardBackSrcId = await uploadImage(idCardBack);
    const handleIdCardSrcId = await uploadImage(handleIdCard);

    //提交数据
    try {
      const base = baseRequest();
      //对手机号进行RSA加密
      const encrypt = new JSEncrypt();
      encrypt.setPublicKey(process.env.NEXT_PUBLIC_RSA_KEY);
      const encrypted_real_name = encrypt.encrypt(realName);
      const encrypted_ID_no = encrypt.encrypt(idNumber);
      const signature = generateSignature({
        mid: parseInt(mid, 10),
        real_name: encrypted_real_name,
        ID_no: encrypted_ID_no,
        ID_card_photos: { image_ids: [idCardFrontSrcId, idCardBackSrcId] },
        full_face_photo_with_ID_card_in_hand: {
          image_ids: [handleIdCardSrcId],
        },
        ...base,
        b_mid: parseInt(mid, 10),
      });
      const detailResponse = await fetch(
        `/api/realname_authentication/create?signature=${signature}`,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            mid: parseInt(mid, 10),
            real_name: encrypted_real_name,
            ID_no: encrypted_ID_no,
            ID_card_photos: { image_ids: [idCardFrontSrcId, idCardBackSrcId] },
            full_face_photo_with_ID_card_in_hand: {
              image_ids: [handleIdCardSrcId],
            },
            ...base,
            b_mid: parseInt(mid, 10),
          }),
        }
      );
      const detailData = await detailResponse.json();
      if (detailData.ret === -1) {
        Toast.show({
          content: detailData.msg,
        });
        return;
      }
      Toast.show({
        content: "提交成功，请耐心等待审核",
      });
      router.back();
    } catch (error) {
      console.error(error);
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <section className="container flex flex-col flex-1 items-center p-4">
      <form
        onSubmit={handleSubmit}
        className="flex flex-col flex-1 w-full max-w-sm"
      >
        <p className="text-white text-base mt-2">
          <span className="text-error">*</span>真实姓名：
        </p>
        <input
          type="text"
          name="realName"
          placeholder="请输入您的姓名"
          value={realName}
          onChange={(e) => setRealName(e.target.value)}
          className="input input-bordered input-md input-primary w-full max-w-sm"
        />
        <p className="text-white text-base mt-2">
          <span className="text-error">*</span>身份证号：
        </p>
        <input
          name="idNumber"
          placeholder="请输入您的身份证号"
          value={idNumber}
          onChange={(e) => setIdNumber(e.target.value)}
          className="input input-bordered input-md input-primary w-full max-w-sm"
        />
        <p className="text-white text-base mt-2">
          <span className="text-error">*</span>身份证照片：
        </p>
        <div className="flex flex-row gap-4">
          <label
            htmlFor="idCardFront"
            className="basis-1/2 aspect-[214/135] rounded-xl overflow-hidden relative"
          >
            {idCardFront ? (
              <div className="relative w-full h-full">
                <Image
                  className="w-full object-cover"
                  src={URL.createObjectURL(idCardFront)}
                  fill
                  alt=""
                />
                <img
                  className="w-full h-full object-cover absolute top-0 left-0 bg-black/50"
                  src="/cdn/images/verification_water_mark.png"
                  alt=""
                />
              </div>
            ) : (
              <div className="flex justify-center items-center w-full h-full bg-[#FFFFFF1A]">
                <svg viewBox="0 0 1024 1024" width="150" height="150">
                  <path
                    d="M361.50303 474.763636c-48.09697 0-88.436364-38.787879-88.436363-88.436363s38.787879-88.436364 88.436363-88.436364 88.436364 38.787879 88.436364 88.436364-40.339394 88.436364-88.436364 88.436363z m0-145.842424c-31.030303 0-57.406061 24.824242-57.40606 57.406061 0 31.030303 24.824242 57.406061 57.40606 57.40606S418.909091 418.909091 418.909091 386.327273c-1.551515-31.030303-26.375758-57.406061-57.406061-57.406061z"
                    fill="#FFFFFF26"
                  ></path>
                  <path
                    d="M263.757576 553.890909h-4.654546c-7.757576-3.10303-12.412121-10.860606-10.860606-20.169697 15.515152-49.648485 63.612121-85.333333 116.363637-85.333333 52.751515 0 100.848485 35.684848 116.363636 85.333333 3.10303 7.757576-1.551515 17.066667-10.860606 20.169697-7.757576 3.10303-17.066667-1.551515-20.169697-10.860606-12.412121-37.236364-46.545455-63.612121-86.884849-63.612121-38.787879 0-74.472727 26.375758-86.884848 63.612121 0 6.206061-6.206061 10.860606-12.412121 10.860606zM754.036364 631.466667H260.654545c-9.309091 0-15.515152-6.206061-15.515151-15.515152s6.206061-15.515152 15.515151-15.515151h493.381819c9.309091 0 15.515152 6.206061 15.515151 15.515151s-6.206061 15.515152-15.515151 15.515152zM754.036364 710.593939H260.654545c-9.309091 0-15.515152-6.206061-15.515151-15.515151s6.206061-15.515152 15.515151-15.515152h493.381819c9.309091 0 15.515152 6.206061 15.515151 15.515152s-6.206061 15.515152-15.515151 15.515151zM754.036364 451.490909H595.781818c-9.309091 0-15.515152-6.206061-15.515151-15.515151s6.206061-15.515152 15.515151-15.515152h158.254546c9.309091 0 15.515152 6.206061 15.515151 15.515152s-6.206061 15.515152-15.515151 15.515151zM754.036364 530.618182H595.781818c-9.309091 0-15.515152-6.206061-15.515151-15.515152s6.206061-15.515152 15.515151-15.515151h158.254546c9.309091 0 15.515152 6.206061 15.515151 15.515151s-6.206061 15.515152-15.515151 15.515152zM754.036364 370.812121H595.781818c-9.309091 0-15.515152-6.206061-15.515151-15.515151s6.206061-15.515152 15.515151-15.515152h158.254546c9.309091 0 15.515152 6.206061 15.515151 15.515152s-6.206061 15.515152-15.515151 15.515151z"
                    fill="#FFFFFF26"
                  ></path>
                  <path
                    d="M822.30303 808.339394H201.69697c-26.375758 0-46.545455-20.169697-46.545455-46.545455V263.757576c0-26.375758 20.169697-46.545455 46.545455-46.545455h620.60606c26.375758 0 46.545455 20.169697 46.545455 46.545455v498.036363c0 24.824242-20.169697 46.545455-46.545455 46.545455zM201.69697 248.242424c-9.309091 0-15.515152 6.206061-15.515152 15.515152v498.036363c0 9.309091 6.206061 15.515152 15.515152 15.515152h620.60606c9.309091 0 15.515152-6.206061 15.515152-15.515152V263.757576c0-9.309091-6.206061-15.515152-15.515152-15.515152H201.69697z"
                    fill="#FFFFFF26"
                  ></path>
                </svg>
              </div>
            )}
            <input
              type="file"
              id="idCardFront"
              name="idCardFront"
              accept="image/*"
              onChange={(e) => setIdCardFront(e.target.files[0])}
              className="w-full h-full opacity-0 cursor-pointer absolute top-0 left-0"
            />
          </label>
          <label
            htmlFor="idCardBack"
            className="basis-1/2 aspect-[214/135] rounded-xl overflow-hidden relative"
          >
            {idCardBack ? (
              <div className="relative w-full h-full">
                <Image
                  className="w-full object-cover"
                  src={URL.createObjectURL(idCardBack)}
                  fill
                  alt=""
                />
                <img
                  className="w-full h-full object-cover absolute top-0 left-0 bg-black/50"
                  src="/cdn/images/verification_water_mark.png"
                  alt=""
                />
              </div>
            ) : (
              <div className="flex justify-center items-center w-full h-full bg-[#FFFFFF1A]">
                <svg viewBox="0 0 1024 1024" width="150" height="150">
                  <path
                    d="M341.333333 513.551515c-48.09697 0-88.436364-38.787879-88.436363-88.436363 0-48.09697 38.787879-88.436364 88.436363-88.436364s88.436364 38.787879 88.436364 88.436364c-1.551515 49.648485-40.339394 88.436364-88.436364 88.436363z m0-144.290909c-31.030303 0-57.406061 24.824242-57.40606 57.406061 0 31.030303 24.824242 57.406061 57.40606 57.40606 31.030303 0 57.406061-24.824242 57.406061-57.40606-1.551515-32.581818-26.375758-57.406061-57.406061-57.406061zM754.036364 631.466667H260.654545c-9.309091 0-15.515152-6.206061-15.515151-15.515152s6.206061-15.515152 15.515151-15.515151h493.381819c9.309091 0 15.515152 6.206061 15.515151 15.515151s-7.757576 15.515152-15.515151 15.515152zM754.036364 710.593939H260.654545c-9.309091 0-15.515152-6.206061-15.515151-15.515151s6.206061-15.515152 15.515151-15.515152h493.381819c9.309091 0 15.515152 6.206061 15.515151 15.515152s-7.757576 15.515152-15.515151 15.515151zM754.036364 390.981818H513.551515c-9.309091 0-15.515152-6.206061-15.515151-15.515151s6.206061-15.515152 15.515151-15.515152h238.933333c9.309091 0 15.515152 6.206061 15.515152 15.515152s-6.206061 15.515152-13.963636 15.515151zM754.036364 510.448485H513.551515c-9.309091 0-15.515152-6.206061-15.515151-15.515152s6.206061-15.515152 15.515151-15.515151h238.933333c9.309091 0 15.515152 6.206061 15.515152 15.515151s-6.206061 15.515152-13.963636 15.515152z"
                    fill="#FFFFFF26"
                  ></path>
                  <path
                    d="M822.30303 806.787879H201.69697c-26.375758 0-46.545455-20.169697-46.545455-46.545455V263.757576c0-26.375758 20.169697-46.545455 46.545455-46.545455h620.60606c26.375758 0 46.545455 20.169697 46.545455 46.545455v496.484848c0 26.375758-20.169697 46.545455-46.545455 46.545455zM201.69697 248.242424c-9.309091 0-15.515152 6.206061-15.515152 15.515152v496.484848c0 9.309091 6.206061 15.515152 15.515152 15.515152h620.60606c9.309091 0 15.515152-6.206061 15.515152-15.515152V263.757576c0-9.309091-6.206061-15.515152-15.515152-15.515152H201.69697z"
                    fill="#FFFFFF26"
                  ></path>
                </svg>
              </div>
            )}
            <input
              type="file"
              id="idCardBack"
              name="idCardBack"
              accept="image/*"
              onChange={(e) => setIdCardBack(e.target.files[0])}
              className="w-full h-full opacity-0 cursor-pointer absolute top-0 left-0"
            />
          </label>
        </div>
        <div className="flex flex-row gap-4">
          <p className="basis-1/2 text-center text-secondary text-base">
            身份证人像面
          </p>
          <p className="basis-1/2 text-center text-secondary text-base">
            身份证国徽面
          </p>
        </div>
        <p className="text-white text-base mt-2">
          <span className="text-error">*</span>本人手持身份证人像面照片：
        </p>
        <div className="flex flex-row gap-4">
          <label
            htmlFor="idCardFront"
            className="basis-1/2 aspect-[214/135] rounded-xl overflow-hidden relative"
          >
            {handleIdCard ? (
              <div className="relative w-full h-full">
                <Image
                  className="w-full object-cover"
                  src={URL.createObjectURL(handleIdCard)}
                  fill
                  alt=""
                />
                <img
                  className="w-full h-full object-cover absolute top-0 left-0 bg-black/50"
                  src="/cdn/images/verification_water_mark.png"
                  alt=""
                />
              </div>
            ) : (
              <div className="flex justify-center items-center w-full h-full bg-[#FFFFFF1A]">
                <svg viewBox="0 0 1024 1024" width="100" height="100">
                  <path
                    d="M371.64357008 315.14947033c6.49709819 44.52423193 21.40220498 69.74825947 31.72112731 81.97809222h207.52495798c10.12782902-12.42092287 25.797301-37.07167852 31.72112729-81.97809222 19.30020283 5.35055124 26.17948435-21.40220498 27.32602968-38.02713377 1.14654691-16.05165376 11.84764942-67.07298383-12.42092286-62.67788785 4.7772778-34.39640288 8.59910032-64.77988999 6.87928152-81.02263542-5.9238247-57.32733659-48.72823625-116.94776702-156.5036295-121.15177291-91.72373949 4.20400432-151.15307823 64.39770821-157.07690294 121.15177291-1.5287287 16.05165376 1.5287287 47.19950756 6.49709817 81.02263542-24.07748219-4.7772778-13.37637813 46.62623408-12.22983275 62.67788785 0.19109168 16.6249272 6.68818983 42.80441155 26.5616661 38.02713377z m0 0M160.87006143 545.79645526h328.10345902v31.72112726H160.87006143v-31.72112726z m0 150.0065313h328.10345902v31.72112729H160.87006143v-31.72112729z m0 149.62434953h709.33024877v31.72112731H160.87006143v-31.72112731z m423.64901951-49.3015097h257.39974276c8.02582687 0 14.52292505-5.9238247 14.52292501-13.37637813 0 0 0-48.15496281-38.60040722-65.92643849-24.07748219-11.27437596-9.17237379-2.67527563-38.60040563-13.94965157-30.0013069-11.27437596-33.82312944-15.0961985-33.82312945-15.09619851l-0.57327345-26.17948435s11.27437596-8.02582687 14.52292502-32.10330748c6.87927995 1.5287287 9.17237379-7.45255342 9.74564726-13.37637968 0.57327345-5.9238247 4.20400432-23.50420873-4.20400433-21.97547846 1.5287287-11.84764942 3.24854908-23.12202537 2.67527562-28.85475997-2.10200217-20.44674974-17.19820066-41.27568286-55.79860787-42.80441154-32.67658252 1.5287287-53.69660572 22.54875191-55.7986079 42.80441154-0.57327345 5.9238247 0.57327345 16.6249272 2.10200218 28.85475997-8.59910032-1.5287287-4.7772778 16.6249272-4.20400434 21.97547846 0.57327345 5.9238247 2.67527563 15.47838028 9.55455559 13.37637968 3.24854908 24.65075407 14.52292505 32.67658252 14.52292659 32.67658095l-0.57327344 26.37057604s-1.14654691 3.82182254-30.57458036 15.47838027c-30.0013069 11.27437596-14.52292505 2.10200217-38.60040724 13.37637813-38.60040722 17.77147413-38.60040722 65.92643692-38.60040565 65.92643848 0.38218179 6.87927995 6.68818983 12.80310465 14.90510685 12.80310466z m0 0"
                    fill="#FFFFFF26"
                  ></path>
                  <path
                    d="M1001.47991057 755.80560036c0-43.377685-23.50420873-78.72954316-53.69660416-82.5513657V448.14889108c0-27.89930315-23.12202537-51.02133009-51.02133008-51.02132853H124.75383973c-27.89930315 0-51.02133009 23.12202537-51.02133009 51.02132853v225.10534358c-30.0013069 3.82182254-53.69660572 39.17368068-53.69660571 82.5513657 0 43.377685 23.50420873 78.72954316 53.69660571 82.55136411v105.10011759c0 27.89930315 23.12202537 51.02133009 51.02133009 51.02133011h772.0081366c27.89930315 0 51.02133009-23.12202537 51.02133008-51.02133011v-105.10011759c30.19239699-3.63073087 53.69660572-39.55586247 53.69660416-82.55136411zM896.95306642 983.77730969h-772.00813503c-21.97547846 0-40.12913593-18.1536559-40.1291359-40.12913594v-105.10011759c30.0013069-3.82182254 53.69660572-39.17368068 53.69660414-82.5513657 0-43.377685-23.50420873-78.72954316-53.69660414-82.55136411V448.14889108c0-21.97547846 18.1536559-40.12913593 40.1291359-40.12913436h772.00813503c21.97547846 0 40.12913593 18.1536559 40.12913593 40.12913436v225.10534358c-30.0013069 3.82182254-53.69660572 39.17368068-53.69660571 82.5513657 0 43.377685 23.50420873 78.72954316 53.69660571 82.55136411v105.10011759c0.19109168 22.54875191-18.1536559 40.32022761-40.12913593 40.32022763z m0 0"
                    fill="#FFFFFF26"
                  ></path>
                </svg>
              </div>
            )}
            <input
              type="file"
              id="handleIdCard"
              name="handleIdCard"
              accept="image/*"
              onChange={(e) => setHandleIdCard(e.target.files[0])}
              className="w-full h-full opacity-0 cursor-pointer absolute top-0 left-0"
            />
          </label>
        </div>
        <div className="flex flex-row gap-4">
          <p className="basis-1/2 text-center text-secondary text-sm">
            手持身份证照片
            <br />
            （需清晰可见身份证号码）
          </p>
        </div>
        <p className="text-error text-base mt-4">重要提示：</p>
        <p className="text-error text-sm">
          1.所有信息仅用于审核用途，预计24小时内完成，请耐心等待，如进度缓慢，请联系客服；
          <br />
          2.请确认当前实名认证人与提现收款人一致，否则无法打款。
        </p>
        <button
          disabled={isSubmitting}
          className="btn btn-md btn-primary text-white rounded-full w-full max-w-sm mt-4"
        >
          {isSubmitting && <span className="loading loading-spinner"></span>}
          {isSubmitting ? "提交中..." : "提交"}
        </button>
      </form>
    </section>
  );
}
