"use client";
import { DepositsTypes } from "@/api/depositsApi";
import { getUserRechargeApi } from "@/api/user";
import Box from "@/components/Box";
import ButtonOwn from "@/components/ButtonOwn";
import { neReg } from "@/utils";
import { Form, Input, Toast } from "antd-mobile";
import { FormInstance } from "antd-mobile/es/components/form";
import { useTranslations } from "next-intl";
import { FC, Fragment, useRef, useState } from "react";
import "./page.scss";

interface Props {
    deposits: DepositsTypes[];
}
const MobileFiled = ({
    value,
    onChange,
    products,
}: {
    value?: any;
    onChange?: (value: any) => void;
    products: DepositsTypes["products"];
}) => {
    const t = useTranslations();
    return (
        <>
            <Input placeholder={t("form.card")} type={"number"} />
        </>
    );
};
const DepositData: FC<Props> = (props) => {
    const { deposits } = props;
    const t = useTranslations();

    const [activeType, setActiveType] = useState<DepositsTypes>(deposits[0]);

    const formInstanceRef = useRef<FormInstance>(null);
    let [amount, setAmount] = useState<number | undefined>(undefined);
    // const ChangeAmount = (e: any) => {
    //     let newAmount = e.target.value.replace(/[^0-9]/g, "");
    //     if (newAmount > activeType.max_amount) newAmount = activeType.max_amount;
    //     // if (newAmount < activeType.min_amount) newAmount = activeType.min_amount;
    //     setAmount(newAmount);
    // };

    // const userRechargeRequest = async () => {
    //     if (!amount) return;
    //     if (amount < activeType.min_amount) {
    //         Toast.show(`Min  ${activeType.min_amount}`);
    //         return;
    //     }
    //     let res = await getUserRechargeApi({
    //         amount: amount,
    //         channel_id: activeType.id,
    //     });
    //     console.log(`🚀🚀🚀🚀🚀-> in DepositData.tsx on 38`, res);
    //     if (res.code === 200) {
    //         setAmount(undefined);
    //         Toast.show({ icon: "success", content: t("RechargeSuc"), maskClickable: false });
    //         await actions();
    //     }
    // };
    const titleChangeHandler = (item: DepositsTypes, index: number) => {
        setAmount(undefined);
        setActiveType(item);
        formInstanceRef.current?.resetFields();
    };

    const isStrictMode = true;

    const onFinish = (values: any) => {
        const params = { ...values, channel_id: activeType.id, amount: +values.amount };
        getUserRechargeApi(params)
            .then((res) => {
                formInstanceRef.current?.resetFields();
                Toast.show({ icon: "success", content: t("code.200"), maskClickable: false });
                setAmount(undefined);
                if (res.data.pay_url) {
                    window.open(res.data.pay_url);
                }
            })
            .catch((error) => {
                Toast.show({ content: t(`code${error.data.code}`), maskClickable: false });
            });
    };
    const onValuesChange = (changeValues: any) => {
        if (changeValues.amount) {
            setAmount(changeValues.amount);
        }
    };
    const amountChange = (value: number) => {
        formInstanceRef.current?.setFieldValue("amount", value);
        setAmount(value);
    };
    const amountValidator = (rules: any, value: any) => {
        if (!value) return Promise.reject(new Error(t("form.amount")));
        if (+value < activeType.min_amount)
            return Promise.reject(
                new Error(t("form.amountMinReg", { amount: activeType.min_amount }))
            );
        if (+value > activeType.max_amount)
            return Promise.reject(
                new Error(t("form.amountMaxReg", { amount: activeType.max_amount }))
            );
        return Promise.resolve();
    };
    return (
        <div className="deposit-box">
            <div className="img-box"></div>

            <div className={"flex flex-wrap"}>
                {deposits.map((item, index) => {
                    return (
                        <Fragment key={item.id}>
                            <p
                                className="btn-box truncate"
                                style={{
                                    borderColor: activeType.id === item.id ? "#ff9323" : "#333",
                                }}
                                onClick={() => titleChangeHandler(item, index)}
                            >
                                {item.name}
                            </p>
                        </Fragment>
                    );
                })}
            </div>

            <Box className={"custom-form"} style={{ padding: 0 }}>
                <Form
                    style={{
                        "--border-bottom": "none",
                        "--border-top": "none",
                        "--border-inner": "none",
                    }}
                    ref={formInstanceRef}
                    footer={
                        <>
                            <ButtonOwn active>{t("DepositPage.DepositarAgora")}</ButtonOwn>
                        </>
                    }
                    // initialValues={params.current}
                    onFinish={onFinish}
                    onValuesChange={onValuesChange}
                >
                    {isStrictMode ? (
                        <>
                            <Form.Item
                                name="user_name"
                                label=""
                                rules={[{ required: true, message: t("form.usernameReg") }]}
                            >
                                <Input placeholder={t("form.username")} />
                            </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>
                        </>
                    ) : null}
                    <Form.Item
                        name="amount"
                        label=""
                        rules={[{ required: true, type: "number", validator: amountValidator }]}
                    >
                        <Input
                            placeholder={`${t("DepositPage.Montante")}(BRL): Mín. ${activeType.min_amount}`}
                            type={"number"}
                            maxLength={activeType.max_amount}
                        />
                    </Form.Item>

                    <div className={"flex flex-col"}>
                        <div className={"flex-1"}>
                            {/*<div className="amount-box">*/}
                            {/*    <span>{t("Montante")} (BRL):</span>*/}
                            {/*    <input*/}
                            {/*        type="text"*/}
                            {/*        value={amount}*/}
                            {/*        onChange={ChangeAmount}*/}
                            {/*        placeholder={`Mín. ${activeType.min_amount}`}*/}
                            {/*    />*/}
                            {/*</div>*/}
                            <ul className="ul-box">
                                {activeType.products.map((item, index) => (
                                    <li
                                        className={amount == item.amount ? "active" : ""}
                                        key={index}
                                        onClick={() => amountChange(item.amount)}
                                    >
                                        {!!item.badge && <span className="hot"></span>}
                                        <div className="amountContent">
                                            {/* <span className="iconfont icon-unit-brl"></span> */}
                                            <span className="iconfont">R$</span>
                                            <span> {item.amount}</span>
                                        </div>
                                        <span className="amountTips">
                                            {t("DepositPage.Oferecer")} 100%
                                        </span>
                                    </li>
                                ))}
                            </ul>
                        </div>
                    </div>
                </Form>
                <div className={"mt-[5px] text-[0.12rem] text-primary-color"}>
                    {t("DepositPage.depositTips")}
                </div>
            </Box>

            {/*<div className="topUp">*/}
            {/*    <ButtonOwn active={amount !== ""} callbackFun={userRechargeRequest}>*/}
            {/*        {t("DepositarAgora")}*/}
            {/*    </ButtonOwn>*/}
            {/*<div className={"mt-[5px] text-[0.12rem] text-primary-color"}>{t("depositTips")}</div>*/}
            {/*</div>*/}
        </div>
    );
};

export default DepositData;
