import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useEffect, useRef, useState } from 'react';
import { Modal, Tabs, Input, Button, Space, Typography, Form } from 'antd';
import { CheckOutlined, CopyOutlined, EditOutlined } from '@ant-design/icons';
import styled from 'styled-components';
import jwtDecode from 'jwt-decode';
import { useSecurityContext } from '../../hooks';
import { copyToClipboard } from '../../utils';
const { TabPane } = Tabs;
const { TextArea } = Input;
const { Text, Link } = Typography;
const FlexBox = styled.div `
  display: flex;
  gap: 8px;

  input {
    text-overflow: ${(props) => (props.editing ? 'unset' : 'ellipsis')};
  }
`;
export function SecurityContext() {
    const { payload, token, isModalOpen, setIsModalOpen, saveToken, onTokenPayloadChange, } = useSecurityContext();
    const [form] = Form.useForm();
    const [editingToken, setEditingToken] = useState(false);
    const [isJsonValid, setIsJsonValid] = useState(true);
    const [tmpPayload, setPayload] = useState(payload || '');
    const [isSubmitting, setSubmitting] = useState(false);
    const inputRef = useRef(null);
    useEffect(() => {
        if (editingToken) {
            inputRef.current?.focus();
        }
    }, [editingToken]);
    useEffect(() => {
        setEditingToken(!token);
        setPayload(payload);
        form.setFieldsValue({
            token,
        });
    }, [form, token, payload]);
    async function handleTokenSave(values) {
        try {
            setSubmitting(true);
            await saveToken(await onTokenPayloadChange(jwtDecode(values?.token), values?.token || null));
        }
        catch (_) {
            await saveToken(values?.token || null);
        }
        finally {
            setEditingToken(false);
            setIsModalOpen(false);
            setSubmitting(false);
        }
    }
    function handlePayloadChange(event) {
        const { value } = event.target;
        setPayload(value);
        try {
            JSON.parse(value);
            setIsJsonValid(true);
        }
        catch (error) {
            setIsJsonValid(false);
        }
    }
    async function handlePayloadSave() {
        if (isJsonValid) {
            if (typeof onTokenPayloadChange !== 'function') {
                throw new Error('Saving token requires the `onTokenPayloadChange` function provided to the `SecurityContext`');
            }
            setSubmitting(true);
            try {
                await saveToken(await onTokenPayloadChange(JSON.parse(tmpPayload || '{}'), null));
            }
            catch (error) {
                console.error(error);
            }
            setSubmitting(false);
        }
        else if (!tmpPayload) {
            await saveToken(null);
        }
        setIsModalOpen(false);
    }
    return (_jsx(Modal, { title: "Security Context", visible: isModalOpen, footer: null, bodyStyle: {
            paddingTop: 8,
        }, onCancel: () => {
            setIsModalOpen(false);
            setEditingToken(false);
        }, children: _jsx("div", { "data-testid": "security-context-modal", children: _jsxs(Space, { direction: "vertical", size: 24, style: { width: '100%' }, children: [_jsxs(Tabs, { defaultActiveKey: "json", style: { minHeight: 200 }, onChange: (tabKey) => {
                            if (tabKey !== 'token' && editingToken && token) {
                                setEditingToken(false);
                                form.resetFields();
                            }
                        }, children: [_jsx(TabPane, { tab: "JSON", children: _jsxs(Space, { direction: "vertical", size: 16, style: { width: '100%' }, children: [_jsx(TextArea, { "data-testid": "security-context-textarea", value: tmpPayload || '', rows: 6, style: { width: '100%' }, onChange: handlePayloadChange }), _jsx(Button, { "data-testid": "save-security-context-payload-btn", type: "primary", disabled: Boolean(tmpPayload && !isJsonValid), loading: isSubmitting, onClick: handlePayloadSave, children: "Save" })] }) }, "json"), _jsx(TabPane, { "data-testid": "security-modal-token-tab", tab: "Token", children: _jsxs(Space, { direction: "vertical", size: 16, style: { width: '100%' }, children: [_jsx(Text, { type: "secondary", children: "Edit or copy the generated token from below" }), _jsx(Form, { form: form, initialValues: {
                                                token,
                                            }, onFinish: handleTokenSave, children: _jsxs(FlexBox, { editing: editingToken, children: [_jsx(Form.Item, { name: "token", style: {
                                                            width: 'auto',
                                                            flexGrow: 1,
                                                        }, children: _jsx(Input, { "data-testid": "security-context-token-input", ref: inputRef, disabled: !editingToken }) }), !editingToken ? (_jsxs(_Fragment, { children: [_jsx(Button, { ghost: true, type: "primary", icon: _jsx(EditOutlined, {}), onClick: () => {
                                                                    setEditingToken(true);
                                                                } }), _jsx(Button, { type: "primary", icon: _jsx(CopyOutlined, {}), disabled: !token, onClick: () => copyToClipboard(token), children: "Copy" })] })) : (_jsx(Button, { type: "primary", htmlType: "submit", loading: isSubmitting, icon: _jsx(CheckOutlined, {}) }))] }) })] }) }, "token")] }), _jsxs(Text, { type: "secondary", children: ["Learn more about Security Context in", ' ', _jsx(Link, { href: "https://cube.dev/embedding/authentication/security-context", target: "_blank", children: "docs" })] })] }) }) }));
}
//# sourceMappingURL=SecurityContext.js.map