import { FC, PropsWithChildren } from 'react';
import { useHistory } from 'react-router-dom';

import HelpIcon from '@servicetitan/anvil2/assets/icons/material/round/help.svg';
import { Chip, Flex, Tooltip as TooltipA2, Button } from '@servicetitan/anvil2';
import { ButtonAppearance } from '@servicetitan/hammer-react/dist/types/props';

import { BrandAction } from '../../../utils/interfaces';
import { BrandActionChipColor, BrandActionChipLabel } from '../../../utils/mappers';
import { ActionStatus } from '../../../enums/brands';

export const SingleActionButtonSection: FC<{
    action: BrandAction;
}> = ({ action }) => {
    const history = useHistory();
    const handleClick = () => {
        if (action.action) {
            action.action();
        }

        if (action.href) {
            history.push(action.href);
        }
    };

    let buttonAppearance: ButtonAppearance | undefined;
    if (action.status === undefined) {
        buttonAppearance = 'primary';
    } else if (!action.disabled) {
        buttonAppearance = 'secondary';
    }

    return (
        <Flex gap="2" alignItems="center" className="qa-brand-card-single-action">
            <ActionChip status={action.status} statusTooltip={action.statusTooltip} />
            <Button
                size="small"
                onClick={handleClick}
                disabled={action.disabled}
                appearance={buttonAppearance}
            >
                {action.name}
            </Button>
            {action.disabled && (
                <DisabledActionHelper>{action.disableTooltipContent?.()}</DisabledActionHelper>
            )}
        </Flex>
    );
};

const ActionChip: FC<{ status?: ActionStatus; statusTooltip?: string }> = ({
    status,
    statusTooltip,
}) => {
    if (status === undefined) {
        return null;
    }

    const chip = (
        <Chip
            label={BrandActionChipLabel[status]}
            color={BrandActionChipColor[status]}
            size="small"
        />
    );

    return statusTooltip ? (
        <TooltipA2>
            <TooltipA2.Trigger>{chip}</TooltipA2.Trigger>
            <TooltipA2.Content>{statusTooltip}</TooltipA2.Content>
        </TooltipA2>
    ) : (
        chip
    );
};

const DisabledActionHelper: FC<PropsWithChildren> = ({ children }) => (
    <TooltipA2>
        <TooltipA2.Trigger>
            <Button icon={HelpIcon} size="small" />
        </TooltipA2.Trigger>
        <TooltipA2.Content>{children}</TooltipA2.Content>
    </TooltipA2>
);
