"use client";

// import { useSignUp } from "@clerk/nextjs";
import * as React from "react";

import { Loading } from "@/components/ui/loading";
import { FadeInStagger } from "@/components/landing/fade-in";
import { Input } from "@/components/ui/input";
import { toast } from "@/components/ui/toaster";
import { useRouter } from "next/navigation";
import service from "@/lib/http/service";

import Image from 'next/image';
import showImage from '@/components/images/show.png';
import { useTranslation } from "react-i18next";

// type Props = {
// setError: (e: string | null) => void;
// setVerification: (b: boolean) => void;
// };

// export const EmailSignUp: React.FC<Props> = ({ setError, setVerification, emailValue, passwordValue }) => {

export function EmailSignUp(props: {
  setError: (e: string | null) => void;
  setVerification: (b: boolean) => void;

  email: (value: string) => void;
  password: (value: string) => void;
  emailValue: string;
  passwordValue: string;
}) {
  // const { signUp, isLoaded: signUpLoaded, setActive } = useSignUp();

  const [isLoading, setIsLoading] = React.useState(false);
  const [showPassword, setShowPassword] = React.useState(false);
  const [showPassword2, setShowPassword2] = React.useState(false);

  const [goPassword, setGoPassword] = React.useState(false);
  const [_transferLoading, setTransferLoading] = React.useState(true);

  const router = useRouter();
  const { t, i18n } = useTranslation()
  const language = i18n.language

  React.useEffect(() => {
    const signUpFromParams = async () => {
      const ticket = new URL(window.location.href).searchParams.get("__clerk_ticket");
      const emailParam = new URL(window.location.href).searchParams.get("email");
      if (!ticket && !emailParam) {
        return;
      }
      if (ticket) {
        // await signUp
        //   ?.create({
        //     strategy: "ticket",
        //     ticket,
        //   })
        //   .then((result) => {
        //     if (result.status === "complete" && result.createdSessionId) {
        //       setActive({ session: result.createdSessionId }).then(() => {
        //         router.push("/app/apis");
        //       });
        //     }
        //   })
        //   .catch((err) => {
        //     setTransferLoading(false);
        //     setError((err as Error).message);
        //     console.error(err);
        //   });
      }

      if (emailParam) {
        // setVerification(true);
        // await signUp
        //   ?.create({
        //     emailAddress: emailParam,
        //   })
        //   .then(async () => {
        //     await signUp.prepareEmailAddressVerification();
        //     // set verification to true so we can show the code input
        //     setVerification(true);
        //     setTransferLoading(false);
        //   })
        //   .catch((err) => {
        //     setTransferLoading(false);
        //     if (err.errors[0].code === "form_identifier_exists") {
        //       toast.error("Sorry, it looks like you have an account. Please use sign in");
        //     } else {
        //       console.log("Supress error");
        //     }
        //   });
      }
    };
    signUpFromParams();
    setTransferLoading(false);
  }, []);

  // const signUpWithCode = async (e: React.FormEvent<HTMLFormElement>) => {
  const signUpWithCode = async (email: string, password: string) => {
    // e.preventDefault();
    // const email = new FormData(e.currentTarget).get("email");
    // const first = new FormData(e.currentTarget).get("first");
    // const last = new FormData(e.currentTarget).get("last");

    console.log("-------------", email)

    if (
      // !signUpLoaded ||
      isLoading ||
      typeof email !== "string"
      // typeof first !== "string" ||
      // typeof last !== "string"
    ) {
      return null;
    }


    setIsLoading(true)

    try {
      // await signUp
      //   .create({
      //     emailAddress: email,
      //     firstName: first,
      //     lastName: last,
      //   })
      //   .then(async () => {
      //     await signUp.prepareEmailAddressVerification();
      //     setIsLoading(false);
      //     // set verification to true so we can show the code input
      //     setVerification(true);
      //   })
      //   .catch((err) => {
      //     setIsLoading(false);
      //     if (err.errors[0].code === "form_identifier_exists") {
      //       toast.error("Sorry, it looks like you have an account. Please use sign in");
      //     } else {
      //       toast.error("Sorry, We couldn't sign you up. Please try again later");
      //     }
      //   });

      await service.post('/api/v1/common/auth-code', {
        user_name: email,
        email: email,

        "action_type": 0, //操作类型: 0=用户注册(默认) 1=重置密码
        language: language  //语言: en=英文 zh-CN=简体中文

      }).then(function (result: any) {
        setIsLoading(false);
        console.log("result:", result)

        if (result && result.header.code != 0) {

          toast.error(result.header.message)
          return
        }

        props.password(password)
        toast.success(result.header.message)
        props.setVerification(true);

        // 自身方法
        // localStorage.setItem("data", JSON.stringify(result.data));
        // []方法
        { {/* localStorage["name"]="bonly"; */ } }

      }).catch((err: any) => {
        setIsLoading(false);
        console.log(err);
        // if (err.errors[0].code === "form_identifier_not_found") {
        //   props.setAccountNotFound(true);
        //   props.email(email);
        // } else {
        //   props.setError("Sorry, We couldn't sign you in. Please try again later");
        // }
      });
    } catch (error) {
      setIsLoading(false);
      console.error(error);
    }
  };

  return (
    <FadeInStagger>
      {!goPassword ?
        <form className="grid gap-2" onSubmit={(e) => {
          e.preventDefault();
          const email = new FormData(e.currentTarget).get("email");

          if (

            typeof email !== "string"
            // typeof first !== "string" ||
            // typeof last !== "string"
          ) {
            return null;
          }

          console.log("------1", email)
          props.email(email)

          setGoPassword(true)
        }}>
          <div className="grid gap-4 mb-0">
            <div className="flex flex-col items-start gap-2">
              <label htmlFor="email" className="text-xs text-black/50">
                {t("email")}
              </label>
              <Input
                name="email"
                placeholder={t("auth.email_address")}
                type="email"
                defaultValue={props.emailValue}
                autoCapitalize="none"
                autoComplete="email"
                autoCorrect="off"
                required
                className="h-10 text-black duration-500 bg-transparent focus:text-black border-black/20 focus:bg-white focus:border-black rounded hover:bg-white/20 hover:border-black/40 placeholder:black/20 "
              />
            </div>
          </div>

          <button
            type="submit"
            className="flex items-center justify-center h-10 gap-2 px-4 mt-8 text-sm font-semibold text-white duration-200 bg-black border border-black rounded hover:border-black/30 hover:bg-black/80 hover:text-white"
            disabled={isLoading}
          >
            {/* {isLoading ? <Loading className="w-4 h-4 animate-spin" /> : "Sign Up with Email"} */}
            {t("next")}
          </button>
        </form> : <form className="grid gap-2" onSubmit={async (e) => {
          e.preventDefault();
          const password = new FormData(e.currentTarget).get("password");
          const confirmPassword = new FormData(e.currentTarget).get("confirmPassword");

          console.log("------1", props.emailValue, password, confirmPassword)

          if (typeof password !== "string" || password != confirmPassword) {
            toast.error("two passwords do not match")
            return
          }

          await signUpWithCode(props.emailValue, password)



          setGoPassword(false)
        }} >

          <div className="grid gap-4 mb-4">
            <label htmlFor="password" className="text-xs text-black/50">
              {t("password")}
            </label>
            <div className="grid gap-1 relative">
              <Input
                name="password"
                placeholder={t("password")}
                type={showPassword ? "text" : "password"}
                // defaultValue={props.passwordValue}
                autoCapitalize="none"
                autoComplete="email"
                autoCorrect="off"
                required
                className="h-10 rounded text-black duration-500 bg-transparent focus:text-black border-black/20 focus:bg-white focus:border-black hover:bg-white/20 hover:border-black/40 placeholder:black/20 "
              />
              <Image src={showImage} width={16} alt="show" className="absolute right-4 top-3" onClick={() => {
                setShowPassword(!showPassword)
                // toast.success('coming soon')
              }} />
            </div>
          </div>

          <div className="grid gap-4 mb-4">
            <label htmlFor="password" className="text-xs text-black/50">


              {t("confirm_password")}
            </label>
            <div className="grid gap-1 relative">
              <Input
                name="confirmPassword"
                placeholder={t("confirm_password")}
                type={showPassword2 ? "text" : "password"}
                // defaultValue={props.passwordValue}
                autoCapitalize="none"
                autoComplete="password"
                autoCorrect="off"
                required
                className="h-10 rounded text-black duration-500 bg-transparent focus:text-black border-black/20 focus:bg-white focus:border-black hover:bg-white/20 hover:border-black/40 placeholder:black/20 "
              />
              <Image src={showImage} width={16} alt="show" className="absolute right-4 top-3" onClick={() => {
                setShowPassword2(!showPassword2)
                // toast.success('coming soon')
              }} />
            </div>
          </div>

          <button
            type="submit"
            className="flex items-center justify-center h-10 gap-2 px-4 mt-8 text-sm font-semibold text-white duration-200 bg-black border border-black rounded hover:border-black/30 hover:bg-black/80 hover:text-white"
            disabled={isLoading}
          >
            {/* {isLoading ? <Loading className="w-4 h-4 animate-spin" /> : "Sign Up with Email"} */}
            {isLoading ? <Loading className="w-4 h-4 animate-spin" /> : "Next"}
          </button>
        </form>}




    </FadeInStagger>
  );
};
