import React from 'react';
import { TruncatedText, GlyphButton, Tooltip } from '@theorchard/suite-components';
import { formatMessage } from '@theorchard/suite-i18n';
import cx from 'classnames';

const CLASS_NAME = 'TextLabelField';

export interface TextLabelFieldProps {
    className?: string;
    testId?: string;
    label: string;
    value?: string | number;
    withCopy?: boolean;
}

export const TextLabelField: React.FC<TextLabelFieldProps> = ({
    className,
    testId = CLASS_NAME,
    label,
    value,
    withCopy,
}) => {
    const normalizedValue = value ? value.toString() : '';

    const [isTooltipVisible, setIsTooltipVisible] = React.useState(false);
    const [isCopyClicked, setIsCopyClicked] = React.useState(false);

    const hideTooltip = () => {
        setIsTooltipVisible(false);
        setIsCopyClicked(false);
    };

    return (
        <div className={cx(CLASS_NAME, className)} data-testid={testId}>
            <span className={`${CLASS_NAME}-label`}>{label}</span>

            {withCopy ? (
                <div className="with-copy-value">
                    <TruncatedText
                        className={`${CLASS_NAME}-value`}
                        maxWidth={128}
                        text={normalizedValue}
                    />

                    <Tooltip
                        id={`${CLASS_NAME}-Tooltip`}
                        show={isTooltipVisible}
                        message={
                            isCopyClicked
                                ? formatMessage('common_copied!')
                                : formatMessage('common_copy')
                        }
                    >
                        <GlyphButton
                            variant="control"
                            size="sm"
                            name="copy"
                            onMouseEnter={() => setIsTooltipVisible(true)}
                            onMouseLeave={hideTooltip}
                            onClick={() => {
                                void navigator.clipboard.writeText(normalizedValue);
                                setIsCopyClicked(true);

                                setTimeout(() => hideTooltip(), 2000);
                            }}
                        />
                    </Tooltip>
                </div>
            ) : (
                <span className={`${CLASS_NAME}-value`}>{normalizedValue}</span>
            )}
        </div>
    );
};
