"use client";
import { loginApi, registerApi, userInfoApi } from "@/api/login";
import Box from "@/components/Box";
import ButtonOwn from "@/components/ButtonOwn";
import { Link, useRouter } from "@/i18n";
import { useUserInfoStore } from "@/stores/useUserInfoStore";
import { emailReg, neReg } from "@/utils";
import { setCookies } from "@/utils/Cookies";
import {
    Checkbox,
    DatePicker,
    DatePickerRef,
    Form,
    Input,
    Radio,
    Space,
    TextArea,
    Toast,
} from "antd-mobile";
import { PickerDate } from "antd-mobile/es/components/date-picker/util";
import clsx from "clsx";
import dayjs from "dayjs";
import { useTranslations } from "next-intl";
import { FC, RefObject, useRef, useState } from "react";
interface MobileFieldProps {
    value?: string;
    onChange?: (value: string) => void;
}

const MobileField: FC<MobileFieldProps> = (props) => {
    const t = useTranslations("form");
    const { value, onChange } = props;

    const changeHandler = (value: string) => {
        let newAmount = value.replace(/[^0-9]/g, "");
        if (onChange) {
            onChange(newAmount);
        }
    };
    return (
        <>
            <Space align="center" className={"text-[#ccc]"}>
                <Space align="center">+55</Space>
                <Input
                    placeholder={t("phone")}
                    maxLength={11}
                    value={value}
                    onChange={(e) => changeHandler(e)}
                />
            </Space>
        </>
    );
};

const SexMobile: FC<MobileFieldProps> = (props) => {
    const { value, onChange } = props;
    const handler = () => {
        console.log(`🚀🚀🚀🚀🚀-> in index.tsx on 58`, 123);
    };
    return (
        <div className={"w-[100%] border-4"} onClick={handler}>
            <Space align="center" className={"border-4 text-[#ccc]"}>
                <div className={"h-full w-[100%]"}>{value}</div>
            </Space>
        </div>
    );
};
interface FormProps {
    /**
     * 通讯地址
     */
    address?: string;
    /**
     * 用户头像
     */
    avatar_url?: string;
    /**
     * 生日：yyyy-MM-dd
     */
    birthday?: string;
    /**
     * 邮箱地址
     */
    email?: string;
    /**
     * 真实姓名
     */
    nick_name?: string;
    /**
     * 外部ID
     */
    open_id?: string;
    /**
     * 身份护照
     */
    passport?: string;
    /**
     * 用户密码
     */
    pwd: string;
    /**
     * 推荐码
     */
    referrer_code?: string;
    /**
     * 用户名
     */
    user_name?: string;
    /**
     * 用户电话号码
     */
    user_phone: string;
    /**
     * 用户类型
     */
    user_type?: string;
    sex?: number;
}
type FormType = "login" | "register";
interface Props {
    type?: FormType;
    isStrictMode?: boolean;
}
const FormComponent: FC<Props> = (props) => {
    const { type = "register", isStrictMode = true } = props;
    const { setUserInfo } = useUserInfoStore();
    const t = useTranslations();

    /// 密码可见
    const [visible, setVisible] = useState(false);
    const spanClassName = clsx("iconfont", {
        "icon-kejian": visible,
        "icon-bukejian": !visible,
    });
    // 是否同意协议
    const [checkBoxValue, setCheckBoxValue] = useState<boolean>(false);
    const router = useRouter();
    /// 初始值
    const params = useRef<FormProps>({
        user_phone: "",
        pwd: "",
        sex: 0,
        address: undefined,
        birthday: undefined,
        email: undefined,
        passport: undefined,
        referrer_code: undefined,
    });

    const onFinish = (values: FormProps) => {
        const newValues = {
            ...values,
            referrer_code: sessionStorage.getItem("shareId") ?? undefined,
        };
        if (isStrictMode) {
            strictHandler(newValues);
        } else {
            looseHandler(newValues);
        }
    };

    /// 严格模式
    const strictHandler = (values: FormProps) => {
        if (type !== "login") {
            if (!checkBoxValue) {
                Toast.show({
                    content: t("form.readyAgreement"),
                });
                return;
            }
            values.birthday = dayjs(values.birthday).format("YYYY/MM/DD");
        }

        looseHandler(values);
    };
    /// 宽松模式
    const looseHandler = async (values: FormProps) => {
        // 请求
        Toast.show({
            icon: "loading",
        });
        // 注册
        if (type === "register") {
            registerApi(values)
                .then((res) => {
                    if (res.code === 200) {
                        router.replace("/login");
                    }
                })
                .catch((error) => {
                    Toast.show({
                        content: t(`code.${error.data.code}`),
                    });
                });
        } else {
            /// 登录
            const loginResult = await loginApi(values).catch((error) => {
                Toast.show({
                    content: t(`code.${error.data.code}`),
                });
            });
            if (loginResult?.code === 200) {
                setCookies("Token", loginResult.data.token as string);
                const result = await userInfoApi();
                if (result.code === 200) {
                    setUserInfo(result.data);
                    router.replace("/");
                }
            }
        }
    };

    const onConfirm = (value: PickerDate) => {
        const isChildren = dayjs().subtract(18, "year").isBefore(value);
        if (isChildren) {
            Toast.show({
                icon: "fail",
                content: t("form.NotSuitableForChildren"),
            });
        }
    };
    const ageValidator = (rule: any, value: PickerDate) => {
        const isChildren = dayjs().subtract(18, "year").isBefore(value);
        if (isChildren) {
            return Promise.reject(new Error(rule.message));
        } else {
            return Promise.resolve();
        }
    };
    return (
        <Box className={"custom-form"}>
            <Form
                style={{
                    "--border-bottom": "none",
                    "--border-top": "none",
                    "--border-inner": "none",
                }}
                initialValues={params.current}
                onFinish={onFinish}
                footer={
                    <ButtonOwn active>
                        {type === "login" ? t("form.loginText") : t("form.registerText")}
                    </ButtonOwn>
                }
            >
                <Form.Item
                    name="user_phone"
                    rules={[
                        { required: true, message: t("form.phoneReg") },
                        { min: 10, message: t("form.phoneMinReg") },
                    ]}
                >
                    <MobileField />
                </Form.Item>

                <Form.Item
                    name="pwd"
                    label=""
                    extra={
                        <span className={spanClassName} onClick={() => setVisible(!visible)}></span>
                    }
                    rules={[
                        { required: true, message: t("form.passwordReg") },
                        { min: 6, max: 20, message: t("form.passwordMinReg") },
                    ]}
                >
                    <Input
                        placeholder={t("form.password")}
                        maxLength={20}
                        type={visible ? "text" : "password"}
                    />
                </Form.Item>

                {type !== "login" && isStrictMode ? (
                    <>
                        <Form.Item
                            name="user_name"
                            label=""
                            rules={[{ required: true, message: t("form.usernameReg") }]}
                        >
                            <Input placeholder={t("form.username")} />
                        </Form.Item>
                        <Form.Item
                            name="birthday"
                            clickable={false}
                            trigger={"onConfirm"}
                            arrowIcon={<i className={"iconfont icon-xiangyou1"}></i>}
                            onClick={(e, datePickerRef: RefObject<DatePickerRef>) => {
                                datePickerRef.current?.open();
                            }}
                            rules={[
                                { required: true, message: t("form.birthdayReg") },
                                {
                                    message: t("form.NotSuitableForChildren"),
                                    validator: ageValidator,
                                },
                            ]}
                        >
                            <DatePicker
                                getContainer={null}
                                min={dayjs().subtract(50, "year").toDate()}
                                max={dayjs().toDate()}
                                style={{ background: "#fff", color: "#000" }}
                            >
                                {(value) =>
                                    value ? (
                                        dayjs(value).format("YYYY/MM/DD")
                                    ) : (
                                        <span className={"text-[#ccc]"}>{t("form.birthday")}</span>
                                    )
                                }
                            </DatePicker>
                        </Form.Item>

                        <Form.Item
                            name="email"
                            label=""
                            rules={[
                                { required: true, message: t("form.emailReg"), pattern: emailReg },
                            ]}
                        >
                            <Input placeholder={t("form.email")} />
                        </Form.Item>
                        <Form.Item name="sex">
                            <Radio.Group>
                                <Radio
                                    value={0}
                                    className={"mr-[0.1rem]"}
                                    style={{ "--icon-size": "18px" }}
                                >
                                    {t("form.sexMan")}
                                </Radio>
                                <Radio value={1} style={{ "--icon-size": "18px" }}>
                                    {t("form.sexWoman")}
                                </Radio>
                            </Radio.Group>
                        </Form.Item>
                        <Form.Item
                            name="passport"
                            label=""
                            rules={[
                                { required: true, message: t("form.cardReg"), pattern: neReg },
                                { min: 11, message: t("form.cardReg") },
                            ]}
                        >
                            <Input placeholder={t("form.card")} maxLength={11} type={"number"} />
                        </Form.Item>

                        <Form.Item
                            name="address"
                            label=""
                            rules={[{ required: true, message: t("form.addressReg") }]}
                        >
                            <TextArea placeholder={t("form.address")} maxLength={40} />
                        </Form.Item>

                        <div className={"flex px-[0.1rem]"}>
                            <Checkbox
                                block
                                style={{ "--icon-size": "16px" }}
                                checked={checkBoxValue}
                                onChange={(value) => setCheckBoxValue(value)}
                            ></Checkbox>
                            <div className={"ml-[10px] select-none break-all text-[12px]"}>
                                {t("form.agreement")}
                                <Link href={"/preventLaunderMoney"}>
                                    {t("form.moneyAgreement")}
                                </Link>
                                、<Link href={"/terms"}>{t("form.serverAgreement")}</Link>
                                {t("form.agreementAnd")}
                                <Link href={"/gamingPolicy"}>{t("form.childrenAgreement")}</Link>
                            </div>
                        </div>
                    </>
                ) : null}
            </Form>
            <div className="mb-[0.2rem] flex justify-between text-[0.12rem]">
                {type == "login" ? (
                    <>
                        <Link className={"text-[#fff]"} href="/resetPhone">
                            {t("LoginPage.forgetPwd")}
                        </Link>
                        <Link className={"text-[#fff]"} href="/register">
                            {t("LoginPage.registerGo")}
                        </Link>
                    </>
                ) : (
                    <Link className={"w-[100%] text-center text-[#fff]"} href="/login" replace>
                        {t("LoginPage.loginGo")}
                    </Link>
                )}
            </div>
        </Box>
    );
};

export default FormComponent;
