import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useCallback, useEffect, useState } from "react";
import { Button } from "../../../components/ui/button";
import { Input } from "../../../components/ui/input";
import { getLicenseStatus, requestLicense, formatRetryTimeSimple, } from "../../../licensing/licenseService";
import { SetupStepError } from "../SetupStepError";
import { SetupStepBackButton, SetupStepFooter, SetupStepLayout, } from "../SetupStepLayout";
import { ArrowRight, KeyRound, RefreshCw } from "lucide-react";
function getErrorMessage(error, fallback) {
    return error instanceof Error ? error.message : fallback;
}
export function LicenseEmailStep({ onNext, onBack, onSkip, skipLabel = "Skip", }) {
    const [email, setEmail] = useState("");
    const [buildDate, setBuildDate] = useState("");
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState(null);
    const [countdownSeconds, setCountdownSeconds] = useState(null);
    useEffect(() => {
        let disposed = false;
        getLicenseStatus()
            .then((status) => {
            if (!disposed) {
                setBuildDate(status.buildDate || "");
            }
        })
            .catch(() => {
            // Non-fatal. License request works without build date as well.
        });
        return () => {
            disposed = true;
        };
    }, []);
    // Countdown timer for rate limit (update frequency depends on remaining time)
    useEffect(() => {
        if (countdownSeconds === null || countdownSeconds <= 0) {
            return;
        }
        // Update every second when < 1 minute, every minute when >= 1 minute
        const updateInterval = countdownSeconds > 60 ? 60000 : 1000;
        const timer = setInterval(() => {
            setCountdownSeconds((prev) => {
                if (prev === null)
                    return null;
                const next = prev - (updateInterval === 60000 ? 60 : 1);
                return next > 0 ? next : 0;
            });
        }, updateInterval);
        return () => clearInterval(timer);
    }, [countdownSeconds]);
    const handleContinue = useCallback(async () => {
        if (!email) {
            setError("Please enter your email address.");
            return;
        }
        try {
            setLoading(true);
            setError(null);
            const response = await requestLicense({
                email,
                // Placeholder values are only used for branching trial-vs-code on this first step.
                name: "Setup",
                companyName: "Setup",
                parheliaBuildDate: buildDate,
            });
            if (response.status === "trial") {
                onNext({ email, mode: "trial_form" });
                return;
            }
            if (response.status === "code_sent") {
                onNext({ email, mode: "code_entry" });
                return;
            }
            if (response.status === "trial_expired") {
                setError(response.message ||
                    "Trial period expired for this email. Use activation code flow.");
                return;
            }
            if (response.status === "rate_limited") {
                const retrySeconds = response.retryAfterSeconds || 60;
                setCountdownSeconds(retrySeconds);
                setError(`Too many requests for sending a new code. If you already have one, use "I already have a code". Otherwise try again in ${formatRetryTimeSimple(retrySeconds)}.`);
                return;
            }
            setError(response.message || "Failed to start license activation.");
        }
        catch (e) {
            setError(getErrorMessage(e, "Failed to contact license service."));
        }
        finally {
            setLoading(false);
        }
    }, [email, buildDate, onNext]);
    return (_jsxs(SetupStepLayout, { icon: KeyRound, title: "License Activation", description: "Enter your email to start license activation. We will detect whether to continue with trial registration or one-time activation code.", descriptionClassName: "max-w-md leading-relaxed", bodyClassName: "flex flex-col items-center text-center", footer: _jsxs(SetupStepFooter, { children: [_jsx(SetupStepBackButton, { onClick: onBack, disabled: loading }), _jsx("div", { className: "flex-1" }), _jsx(Button, { type: "button", variant: "ghost", size: "lg", onClick: onSkip, disabled: loading, children: skipLabel }), _jsx(Button, { type: "submit", form: "license-email-form", size: "lg", disabled: loading || !email, className: "min-w-[220px]", children: loading ? (_jsxs(_Fragment, { children: [_jsx(RefreshCw, { strokeWidth: 1, className: "mr-2 h-4 w-4 animate-spin" }), "Checking..."] })) : (_jsxs(_Fragment, { children: ["Continue", _jsx(ArrowRight, { className: "ml-2 h-4 w-4", strokeWidth: 1 })] })) })] }), children: [_jsxs("form", { id: "license-email-form", className: "w-full max-w-md", onSubmit: (e) => {
                    e.preventDefault();
                    if (loading)
                        return;
                    void handleContinue();
                }, children: [_jsx("div", { className: "mb-4 space-y-4", children: _jsx(Input, { id: "email", type: "email", "data-testid": "license-email-input", value: email, onChange: (e) => {
                                setEmail(e.target.value);
                                setError(null);
                                setCountdownSeconds(null);
                            }, placeholder: "you@company.com", className: `h-11 rounded-xl bg-white autofill:bg-white autofill:shadow-[inset_0_0_0_1000px_white] autofill:[-webkit-text-fill-color:var(--color-neutral-grey-100)] ${error ? "border-feedback-red" : "border-border-default"}` }) }), error && (_jsx(SetupStepError, { className: "mb-8", helper: countdownSeconds !== null && countdownSeconds > 0
                            ? `Retry available in ${formatRetryTimeSimple(countdownSeconds)}`
                            : undefined, children: error }))] }), _jsx(Button, { type: "button", variant: "link", onClick: () => {
                    if (!email) {
                        setError("Please enter your email address first.");
                        return;
                    }
                    onNext({ email, mode: "code_entry" });
                }, disabled: loading, className: "mt-5", children: "I already have a code" })] }));
}
//# sourceMappingURL=LicenseEmailStep.js.map