import { jsx, jsxs } from "react/jsx-runtime";
import { useEffect, useRef, useState } from "react";
import { useForm } from "@tachybase/schema";
import { App, Button, Input } from "antd";
import { createStyles } from "antd-style";
import { useTranslation } from "react-i18next";
import { useAPIClient } from "../api-client/index.mjs";
function _tagged_template_literal(strings, raw) {
    if (!raw) raw = strings.slice(0);
    return Object.freeze(Object.defineProperties(strings, {
        raw: {
            value: Object.freeze(raw)
        }
    }));
}
function _templateObject() {
    const data = _tagged_template_literal([
        "\n      display: flex;\n      gap: 0.5em;\n    "
    ]);
    _templateObject = function() {
        return data;
    };
    return data;
}
const useStyles = createStyles((param)=>{
    let { css } = param;
    return {
        field: css(_templateObject())
    };
});
function VerificationCode(param) {
    let { targetFieldName = 'phone', actionType, value, onChange } = param;
    const { message } = App.useApp();
    const { t } = useTranslation();
    const { styles } = useStyles();
    const api = useAPIClient();
    const form = useForm();
    const [count, setCountdown] = useState(0);
    const timer = useRef(null);
    useEffect(()=>{
        if (count <= 0 && timer.current) clearInterval(timer.current);
    }, [
        count
    ]);
    async function onGetCode() {
        if (count > 0) return;
        try {
            const { data: { data } } = await api.resource('verifications').create({
                values: {
                    type: actionType,
                    phone: form.values[targetFieldName]
                }
            });
            message.success(t('Operation succeeded'));
            if (value) onChange('');
            const expiresIn = data.expiresAt ? Math.ceil((Date.parse(data.expiresAt) - Date.now()) / 1000) : 60;
            setCountdown(expiresIn);
            timer.current = setInterval(()=>{
                setCountdown((count)=>count - 1);
            }, 1000);
        } catch (err) {
            console.error(err);
        }
    }
    return /*#__PURE__*/ jsxs("fieldset", {
        className: styles.field,
        children: [
            /*#__PURE__*/ jsx(Input, {
                value: value,
                onChange: onChange,
                placeholder: t('Verification code')
            }),
            /*#__PURE__*/ jsx(Button, {
                onClick: onGetCode,
                disabled: count > 0,
                children: count > 0 ? t('Retry after {{count}} seconds', {
                    count
                }) : t('Send code')
            })
        ]
    });
}
export { VerificationCode as default };
