import {
    Icon,
    BodyText,
    IconNameType,
    Tooltip,
    useFocusVisible,
} from '@servicetitan/design-system';
import classnames from 'classnames';
import { ReactNode, FC, useRef } from 'react';
import * as Styles from './action-button.module.less';

export interface ActionButtonProps {
    children: ReactNode;
    iconName?: IconNameType;
    hover?: 'primary' | 'negative' | 'none';
    disabled?: boolean;
    tooltip?: string;
    qaPrefix?: string;
    active?: boolean;
    onClick?(): void;
}

export const ActionButton: FC<ActionButtonProps> = ({
    active,
    children,
    disabled,
    iconName,
    onClick,
    qaPrefix,
    tooltip,
}) => {
    const buttonRef = useRef<HTMLButtonElement>(null);
    const { blurFunction, focusFunction, isFocusVisible } = useFocusVisible(buttonRef);

    const handleClick = () => {
        if (disabled) {
            return;
        }

        if (onClick) {
            onClick();
        }
    };

    const getButton = () => {
        const classes = classnames(Styles.actionButton, qaPrefix, {
            [Styles.primary]: !disabled,
            [Styles.focusVisible]: isFocusVisible,
        });

        return (
            <button
                type="button"
                ref={buttonRef}
                className={classes}
                onClick={handleClick}
                disabled={disabled}
                onFocus={focusFunction}
                onBlur={blurFunction}
            >
                {iconName && <Icon name={iconName} size="20px" className="m-r-1" />}
                <BodyText className={`${qaPrefix}-text ${active ? 'c-blue-500' : 'c-neutral-100'}`}>
                    {children}
                </BodyText>
            </button>
        );
    };

    if (!tooltip) {
        return getButton();
    }

    return (
        <Tooltip text={tooltip} direction="l" el="div" className={`${qaPrefix}-tooltip`}>
            {getButton()}
        </Tooltip>
    );
};
