import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
/*
 * Copyright (c) 2023-2025 Datalayer, Inc.
 * Distributed under the terms of the Modified BSD License.
 */
/**
 * SignInSimple – Generic handle + password sign-in form.
 *
 * Posts to `loginUrl` (default `/api/iam/v1/login`) with
 * `{ handle, password }`, then calls `onSignIn(token, handle)` on
 * success so the caller can persist credentials as needed.
 *
 * @module views/signin
 */
import { useState, useCallback, useRef, useMemo, useEffect, } from 'react';
import { Box, Button, FormControl, Heading, Text, Textarea, TextInput, } from '@primer/react';
import { EyeIcon, EyeClosedIcon, KeyIcon, LinkExternalIcon, TelescopeIcon, } from '@primer/octicons-react';
import { coreStore } from '../../state/index.js';
// ── Component ────────────────────────────────────────────────────────
export const SignInSimple = ({ onSignIn, onApiKeySignIn, loginUrl: loginUrlProp, title = 'Datalayer OTEL', description = 'Sign in to access the observability dashboard.', leadingIcon = _jsx(TelescopeIcon, { size: 24 }), }) => {
    const loginUrl = useMemo(() => {
        if (loginUrlProp)
            return loginUrlProp;
        const iamRunUrl = coreStore.getState().configuration?.iamRunUrl;
        return iamRunUrl ? `${iamRunUrl}/api/iam/v1/login` : '/api/iam/v1/login';
    }, [loginUrlProp]);
    const [handle, setHandle] = useState('');
    const [password, setPassword] = useState('');
    const [showPassword, setShowPassword] = useState(false);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState(null);
    // API Key dialog state
    const [showApiKeyDialog, setShowApiKeyDialog] = useState(false);
    const [apiKey, setApiKey] = useState('');
    const apiKeyRef = useRef(null);
    useEffect(() => {
        if (showApiKeyDialog) {
            apiKeyRef.current?.focus();
        }
    }, [showApiKeyDialog]);
    const closeApiKeyDialog = useCallback(() => {
        setShowApiKeyDialog(false);
        setApiKey('');
    }, []);
    const handleApiKeyAuthenticate = useCallback(() => {
        if (!apiKey.trim() || !onApiKeySignIn)
            return;
        onApiKeySignIn(apiKey.trim());
        closeApiKeyDialog();
    }, [apiKey, onApiKeySignIn, closeApiKeyDialog]);
    const handleSignUp = useCallback(() => {
        window.open('https://datalayer.ai/signup', '_blank', 'noopener,noreferrer');
    }, []);
    const submit = useCallback(async () => {
        if (!handle || !password || loading)
            return;
        setLoading(true);
        setError(null);
        try {
            const resp = await fetch(loginUrl, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ handle, password }),
            });
            if (!resp.ok) {
                throw new Error(`HTTP ${resp.status}`);
            }
            const data = await resp.json();
            if (data.success && data.token) {
                onSignIn(data.token, handle);
            }
            else {
                setError(data.message || 'Invalid username or password.');
            }
        }
        catch (err) {
            setError(err instanceof Error ? err.message : String(err));
        }
        finally {
            setLoading(false);
        }
    }, [handle, password, loading, loginUrl, onSignIn]);
    const handleKeyDown = useCallback((e) => {
        if (e.key === 'Enter')
            submit();
    }, [submit]);
    return (_jsx(Box, { sx: {
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            height: '100vh',
            bg: 'canvas.default',
            color: 'fg.default',
        }, children: _jsxs(Box, { sx: {
                width: 360,
                p: 4,
                borderRadius: 2,
                border: '1px solid',
                borderColor: 'border.default',
                bg: 'canvas.subtle',
            }, children: [_jsxs(Box, { sx: {
                        display: 'flex',
                        alignItems: 'center',
                        gap: 2,
                        mb: 4,
                        justifyContent: 'center',
                    }, children: [leadingIcon, _jsx(Heading, { sx: { fontSize: 3 }, children: title })] }), _jsx(Text, { as: "p", sx: { fontSize: 1, color: 'fg.muted', mb: 3, textAlign: 'center' }, children: description }), _jsxs(FormControl, { required: true, sx: { mb: 3 }, children: [_jsx(FormControl.Label, { children: "Username" }), _jsx(TextInput, { autoFocus: true, block: true, placeholder: "Your username", value: handle, onChange: e => setHandle(e.target.value), onKeyDown: handleKeyDown })] }), _jsxs(FormControl, { required: true, sx: { mb: 3 }, children: [_jsx(FormControl.Label, { children: "Password" }), _jsx(TextInput, { block: true, placeholder: "Your password", type: showPassword ? 'text' : 'password', value: password, onChange: e => setPassword(e.target.value), onKeyDown: handleKeyDown, trailingAction: _jsx(TextInput.Action, { onClick: () => setShowPassword(!showPassword), icon: showPassword ? EyeClosedIcon : EyeIcon, "aria-label": showPassword ? 'Hide password' : 'Show password', sx: { color: 'var(--fgColor-muted)' } }) })] }), error && (_jsx(Text, { sx: { color: 'danger.fg', fontSize: 1, mb: 3, display: 'block' }, children: error })), _jsx(Button, { variant: "primary", block: true, disabled: loading || !handle || !password, onClick: submit, children: loading ? 'Signing in…' : 'Sign in' }), _jsx(Box, { sx: { mt: 2, display: 'flex', justifyContent: 'center' }, children: _jsx(Button, { size: "small", variant: "invisible", leadingVisual: LinkExternalIcon, onClick: handleSignUp, children: "Sign Up" }) }), onApiKeySignIn && (_jsxs(_Fragment, { children: [_jsxs(Box, { sx: {
                                display: 'flex',
                                alignItems: 'center',
                                gap: 2,
                                my: 3,
                            }, children: [_jsx(Box, { sx: { flex: 1, height: '1px', bg: 'border.default' } }), _jsx(Text, { sx: { fontSize: 0, color: 'fg.muted' }, children: "or" }), _jsx(Box, { sx: { flex: 1, height: '1px', bg: 'border.default' } })] }), _jsx(Button, { block: true, leadingVisual: KeyIcon, onClick: () => setShowApiKeyDialog(true), children: "Sign In with an API Key" }), showApiKeyDialog && (_jsx(Box, { role: "dialog", "aria-modal": "true", "aria-labelledby": "signin-api-key-title", onKeyDown: event => {
                                if (event.key === 'Escape') {
                                    closeApiKeyDialog();
                                }
                            }, onClick: closeApiKeyDialog, sx: {
                                position: 'fixed',
                                inset: 0,
                                zIndex: 200,
                                p: 3,
                                bg: 'canvas.backdrop',
                                display: 'flex',
                                alignItems: 'center',
                                justifyContent: 'center',
                            }, children: _jsxs(Box, { as: "form", onClick: event => event.stopPropagation(), onSubmit: event => {
                                    event.preventDefault();
                                    handleApiKeyAuthenticate();
                                }, sx: {
                                    width: 'min(560px, 100%)',
                                    p: 3,
                                    borderRadius: 2,
                                    border: '1px solid',
                                    borderColor: 'border.default',
                                    bg: 'canvas.overlay',
                                    color: 'fg.default',
                                    boxShadow: 'shadow.large',
                                }, children: [_jsx(Heading, { id: "signin-api-key-title", sx: { fontSize: 2, mb: 2 }, children: "Enter your API Key" }), _jsxs(FormControl, { required: true, children: [_jsx(FormControl.Label, { children: "API Key" }), _jsx(Textarea, { block: true, required: true, autoFocus: true, placeholder: "Paste your API key here", value: apiKey, onInput: (e) => setApiKey(e.target.value), ref: apiKeyRef })] }), _jsxs(Box, { sx: {
                                            mt: 3,
                                            display: 'flex',
                                            justifyContent: 'flex-end',
                                            gap: 2,
                                        }, children: [_jsx(Button, { type: "button", onClick: closeApiKeyDialog, children: "Cancel" }), _jsx(Button, { type: "submit", variant: "primary", disabled: !apiKey.trim(), children: "Authenticate" })] })] }) }))] }))] }) }));
};
export default SignInSimple;
