"use client";
import ButtonOwn from "@/components/ButtonOwn";
import { Link, useRouter } from "@/i18n";
import { useUserInfoStore } from "@/stores/useUserInfoStore";
import { setCookies } from "@/utils/Cookies";
import { Toast } from "antd-mobile";
import clsx from "clsx";
import { useTranslations } from "next-intl";
import { useSearchParams } from "next/navigation";
import { FC, PropsWithChildren, useState } from "react";
import { useFormStatus } from "react-dom";
import { loginAction } from "./action";
import "./style.scss";

/**
 * @description 登录注册From表单
 * @param {string} type 使用类型
 * @param {string} msgError 错误提示 login 或 register
 * @param {(params: any) => void} callbackFun 回调方法
 */
export interface FromComProps {
    type?: string;
    msgError?: string;
    callbackFun?: (params: any) => void;
}
const initialState = {
    message: "",
};
const Submit = (props: { text: string }) => {
    const { text } = props;
    const { pending, data } = useFormStatus();
    return (
        <ButtonOwn disabled={pending} type={"submit"} active={true}>
            {text}
        </ButtonOwn>
    );
};

const FromCom: FC<PropsWithChildren<FromComProps>> = ({ type = "login", msgError = "" }) => {
    const t = useTranslations("LoginPage");
    let [pwdVisible, setPwdVisible] = useState(false);
    const searchParams = useSearchParams();
    const router = useRouter();
    const { setUserInfo } = useUserInfoStore();
    const [loginFormStatus, setLoginFormStatus] = useState<{ success?: boolean; message?: string }>(
        {}
    );

    const formAction = async (formData: FormData) => {
        Toast.show({ icon: "loading", duration: 3000, maskClickable: false });
        const result = await loginAction(formData);
        setUserInfo(result.user);
        setCookies("Token", result.token!);
        setLoginFormStatus(result);
        Toast.clear();
        if (result.success) {
            router.replace(searchParams.get("redirect") || "/");
        }
    };
    const onsubmit = (e: React.FormEvent<HTMLFormElement>) => {
        e.preventDefault();
        const formData = new FormData(e.target as HTMLFormElement);
        formAction(formData);
    };

    const spanClassName = clsx("iconfont", {
        "icon-kejian": pwdVisible,
        "icon-bukejian": !pwdVisible,
    });

    return (
        <div className="FromCom">
            <form onSubmit={onsubmit}>
                <div className="phoneInput">
                    <span className="after">{t("areaCode")}</span>
                    <input name="userPhone" type="tel" placeholder={t("Celular")} maxLength={11} />
                </div>
                <div className="passwordInput">
                    <input
                        name="pwd"
                        type={pwdVisible ? "text" : "password"}
                        placeholder={t("Senha")}
                        maxLength={12}
                    />
                    <span
                        className={spanClassName}
                        onClick={() => setPwdVisible(!pwdVisible)}
                    ></span>
                </div>
                <div className="btnContent">
                    <div className="tips"> {loginFormStatus.message} </div>
                    <Submit text={type == "login" ? "Login" : t("register")} />
                </div>
            </form>

            <div className="link">
                {type == "login" ? (
                    <>
                        <Link href="/resetPhone">{t("forgetPwd")}</Link>
                        <Link href="/register">{t("registerGo")}</Link>
                    </>
                ) : (
                    <Link href="/login" className="active" replace>
                        {t("loginGo")}
                    </Link>
                )}
            </div>
        </div>
    );
};

export default FromCom;
