var __rest = (this && this.__rest) || function (s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
};
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
// ============================================================================
// Chatbot Main - Message - Content - Code Block
// ============================================================================
import { useState, useRef, useCallback, useEffect } from 'react';
// Import PatternFly components
import { CodeBlock, CodeBlockAction, CodeBlockCode, Button, Tooltip, ExpandableSection, ExpandableSectionToggle, ExpandableSectionVariant, getUniqueId } from '@patternfly/react-core';
import { CheckIcon } from '@patternfly/react-icons/dist/esm/icons/check-icon';
import { CopyIcon } from '@patternfly/react-icons/dist/esm/icons/copy-icon';
import { css } from '@patternfly/react-styles';
const DEFAULT_EXPANDED_TEXT = 'Show less';
const DEFAULT_COLLAPSED_TEXT = 'Show more';
const CodeBlockMessage = (_a) => {
    var _b;
    var { children, className, 'aria-label': ariaLabel, isExpandable = false, expandableSectionProps, expandableSectionToggleProps, expandedText = DEFAULT_EXPANDED_TEXT, collapsedText = DEFAULT_COLLAPSED_TEXT, customActions, isPrimary, shouldRetainStyles } = _a, props = __rest(_a, ["children", "className", 'aria-label', "isExpandable", "expandableSectionProps", "expandableSectionToggleProps", "expandedText", "collapsedText", "customActions", "isPrimary", "shouldRetainStyles"]);
    const [copied, setCopied] = useState(false);
    const [isExpanded, setIsExpanded] = useState(false);
    const buttonRef = useRef();
    const tooltipID = getUniqueId();
    const toggleId = getUniqueId();
    const contentId = getUniqueId();
    const codeBlockRef = useRef(null);
    const language = (_b = /language-(\w+)/.exec(className || '')) === null || _b === void 0 ? void 0 : _b[1];
    // Get custom toggle text from data attributes if available - for use with rehype plugins
    const customExpandedText = props['data-expanded-text'];
    const customCollapsedText = props['data-collapsed-text'];
    const finalExpandedText = customExpandedText || expandedText;
    const finalCollapsedText = customCollapsedText || collapsedText;
    if ((customExpandedText && expandedText !== DEFAULT_EXPANDED_TEXT) ||
        (customCollapsedText && collapsedText !== DEFAULT_COLLAPSED_TEXT)) {
        // eslint-disable-next-line no-console
        console.error('Message:', 'Custom rehype plugins that rely on data-expanded-text or data-collapsed-text will override expandedText and collapsedText props if both are passed in.');
    }
    const onToggle = (isExpanded) => {
        setIsExpanded(isExpanded);
    };
    // Handle clicking copy button
    const handleCopy = useCallback((_event, text) => {
        let textToCopy = '';
        if (typeof text === 'string') {
            textToCopy = text;
        }
        else {
            if (codeBlockRef.current) {
                const codeElement = codeBlockRef.current.querySelector('code');
                textToCopy = (codeElement === null || codeElement === void 0 ? void 0 : codeElement.textContent) || '';
            }
        }
        navigator.clipboard.writeText(textToCopy);
        setCopied(true);
    }, []);
    // Reset copied state
    useEffect(() => {
        if (copied) {
            const timer = setTimeout(() => {
                setCopied(false);
            }, 3000);
            return () => clearTimeout(timer);
        }
    });
    if (!String(children).includes('\n')) {
        return (_jsx("code", Object.assign({}, props, { className: `pf-chatbot__message-inline-code ${isPrimary ? 'pf-m-primary' : ''}`, children: children })));
    }
    // Setup code block header
    const actions = (_jsxs(_Fragment, { children: [_jsxs(CodeBlockAction, { className: "pf-chatbot__message-code-block-default-action", children: [language && _jsx("div", { className: "pf-chatbot__message-code-block-language", children: language }), _jsx(Button, { ref: buttonRef, "aria-label": ariaLabel !== null && ariaLabel !== void 0 ? ariaLabel : 'Copy code', variant: "plain", className: "pf-chatbot__button--copy", onClick: (event) => handleCopy(event, children), children: copied ? _jsx(CheckIcon, {}) : _jsx(CopyIcon, {}) }), _jsx(Tooltip, { id: tooltipID, content: "Copy", position: "top", triggerRef: buttonRef })] }), customActions] }));
    return (_jsx("div", { className: css('pf-chatbot__message-code-block', shouldRetainStyles && 'pf-m-markdown'), ref: codeBlockRef, children: _jsxs(CodeBlock, { actions: actions, children: [_jsx(CodeBlockCode, { children: _jsx(_Fragment, { children: isExpandable ? (_jsx(ExpandableSection, Object.assign({ variant: ExpandableSectionVariant.truncate, isExpanded: isExpanded, isDetached: true, toggleId: toggleId, contentId: contentId }, expandableSectionProps, { children: children }))) : (children) }) }), isExpandable && (_jsx(ExpandableSectionToggle, Object.assign({ isExpanded: isExpanded, onToggle: onToggle, direction: "up", toggleId: toggleId, contentId: contentId, hasTruncatedContent: true, className: "pf-chatbot__message-code-toggle" }, expandableSectionToggleProps, { children: isExpanded ? finalExpandedText : finalCollapsedText })))] }) }));
};
export default CodeBlockMessage;
