"use client";

import { Loading } from "@/components/ui/loading";
import { Input } from "@/components/ui/input";
// import { useSignIn } from "@clerk/nextjs";
import { useRouter } from "next/navigation";
import * as React from "react";

import Image from 'next/image';
import showImage from '@/components/images/show.png';
import md5 from "md5";


import service from '@/lib/http/service';
import { UserDataStorageName } from '@/lib/http/service';


import { useTranslation } from "react-i18next";
import { toast } from "@/components/ui/toaster";

export function EmailSignIn(props: {
  setError: (err: string) => void;
  verification: (value: boolean) => void;
  setAccountNotFound: (value: boolean) => void;
  email: (value: string) => void;
  emailValue: string;
  passwordValue: string;
}) {
  // const { signIn, isLoaded: signInLoaded, setActive } = useSignIn();
  const param = "__clerk_ticket";
  const [isLoading, setIsLoading] = React.useState(false);
  const [showPassword, setShowPassword] = React.useState(false);

  const { t } = useTranslation();

  const router = useRouter();
  React.useEffect(() => {
    const signUpOrgUser = async () => {
      const ticket = new URL(window.location.href).searchParams.get(param);
      // if (!signInLoaded) {
      //   return;
      // }
      if (!ticket) {
        return;
      }
      setIsLoading(true);
      // await signIn
      //   .create({
      //     strategy: "ticket",
      //     ticket,
      //   })
      //   .then((result) => {
      //     if (result.status === "complete" && result.createdSessionId) {
      //       setActive({ session: result.createdSessionId }).then(() => {
      //         router.push("/app");
      //       });
      //     }
      //   })
      //   .catch((err) => {
      //     setIsLoading(false);
      //     console.error(err);
      //   });


    };
    signUpOrgUser();
  }, []);



  const signInWithCode = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    const email = new FormData(e.currentTarget).get("email");
    const password = new FormData(e.currentTarget).get("password");
    if (isLoading || typeof email !== "string" || typeof password !== "string") {
      return null;
    }


    console.log(email, password, (md5(password)))
    // d41d8cd98f00b204e9800998ecf8427e

    setIsLoading(true);
    // await signIn
    //   .create({
    //     identifier: email,
    //   })
    //   .then(async () => {
    //     const firstFactor = signIn.supportedFirstFactors.find((f) => f.strategy === "email_code") as
    //       | { emailAddressId: string }
    //       | undefined;

    //     if (firstFactor) {
    //       await signIn.prepareFirstFactor({
    //         strategy: "email_code",
    //         emailAddressId: firstFactor.emailAddressId,
    //       });

    //       setIsLoading(false);
    //       props.verification(true);
    //     }
    //   })
    //   .catch((err) => {
    //     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");
    //     }
    //   });

    // console.log(process.env.NEXT_PUBLIC_CLIENT_BASE_URL)

    await service.post('/api/v1/customer/login', {
      user_name: email,
      password: md5(password),

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

      if (result && result.header.code != 0) {
        toast.error(result.header.message)
        return
      }

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

      // router.push("/");
      window.location.href = `/manage`

    }).catch((err) => {
      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");
      // }
    });
  };
  return (
    <>
      <form className="grid gap-2" onSubmit={signInWithCode}>
        <div className="grid gap-1">
          <Input
            name="email"
            placeholder={t("auth.email_address")}
            type="email"
            defaultValue={props.emailValue}
            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 "
          />
        </div>
        <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>
        <button
          type="submit"
          className="flex items-center justify-center h-10 gap-2 px-4 text-sm font-semibold text-white duration-200 bg-black border border-black rounded hover:border-black/80 hover:bg-black/80 hover:text-white"
          disabled={isLoading}
        >
          {isLoading ? <Loading className="w-4 h-4 animate-spin" /> : t("auth.sign_in")}
        </button>
      </form>
    </>
  );
}
