import React, { useEffect, useMemo, useState } from 'react';
import { GlyphButton } from '@theorchard/suite-components';
import { MASK_CHAR } from '@theorchard/accounting-apps-shared';
import cx from 'classnames';
import './masked-value.scss';

const CLASS_NAME = 'MaskedValue';
export const DEFAULT_LENGTH = 1;
export const UNMASKED_TIMEOUT = 1000 * 60 * 5; // 5 minutes

interface MaskedValueProps {
    isShowDisabled?: boolean;
    maskedValue?: string | number;
    value: string | number;
}

export const MaskedValue: React.FC<MaskedValueProps> = ({
    isShowDisabled = false,
    maskedValue,
    value,
}) => {
    const [show, setShow] = useState(false);

    useEffect(() => {
        const timer = setTimeout(() => {
            setShow(false);
        }, UNMASKED_TIMEOUT);

        return () => clearTimeout(timer);
    }, [show]);

    const displayValue = useMemo(() => {
        if (show) return value;
        if (maskedValue) return maskedValue;
        return MASK_CHAR.repeat(value?.toString().length || DEFAULT_LENGTH);
    }, [show, maskedValue, value]);

    return (
        <span className={CLASS_NAME} data-dd-privacy="mask">
            <GlyphButton
                variant="control"
                name="preview"
                size="lg"
                onClick={() => setShow(!show)}
                disabled={isShowDisabled}
            />
            <span className={cx({ ['show']: show })}>{displayValue}</span>
        </span>
    );
};
