"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 toast from "react-hot-toast";
import md5 from "md5";


import { getService }  from '@/lib/http/service';
import { useTranslation } from "react-i18next";

export function MixSignIn(props: {
  setError: (err: string) => void;
  verification: (value: boolean) => void;
  setAccountNotFound: (value: boolean) => void;
  username: (value: string) => void;
  usernameValue: string;
  passwordValue: string;
}) {
  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 (!ticket) {
        return;
      }
      setIsLoading(true);
    };
    signUpOrgUser();
  }, []);

  const signInWithCode = async (e: React.FormEvent<HTMLFormElement>) => {

    e.preventDefault();
    const user = new FormData(e.currentTarget).get("username");
    const password = new FormData(e.currentTarget).get("password");
    if (isLoading || typeof user !== "string" || typeof password !== "string") {
      return null;
    }

    console.log("--username:", user, "--password:", password, "--md5 password:", (md5(password)))
    setIsLoading(true);

    const service = await getService();
    await service.post('/api/v1/customer/login', {
      user_name: user,
      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("UserData", JSON.stringify(result.data));
      console.log("--result.data:", result.data)
      window.location.href = `/`
    }).catch((err) => {
      setIsLoading(false);
      console.log(err);
    });
  };
  return (
    <>
      <form className="grid gap-2" onSubmit={signInWithCode}>
        <div className="grid gap-1">
          <Input
            name="username"
            placeholder={t("auth.mixplacehoder")}
            type="text"
            defaultValue={props.usernameValue}
            autoCapitalize="none"
            autoComplete="off"
            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="off"
            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>
    </>
  );
}
