import type { FC, BaseSyntheticEvent } from 'react';
import React from 'react';
import { BsOverlayTrigger, BsTooltip } from '@theorchard/suite-components';
import { formatMessage } from '@theorchard/suite-i18n';
import { GlyphIcon, StoreIcon } from '@theorchard/suite-icons';
import cx from 'classnames';
import useSpotifyPlayer from './useSpotifyPlayer';

export const CLASSNAME = 'SpotifyPlayButton';
export const TEST_ID = CLASSNAME;
export const TEST_CONTENT_ID = `${TEST_ID}-content`;

export const TERM_PLAY_HINT = 'spotifyPlayer.playHint';

export type Positions = 'left' | 'right' | 'top' | 'bottom';
export interface Props {
    trackIds: string[];
    tooltipPlacement?: Positions;
}

const SpotifyPlayButton: FC<Props> = ({ trackIds, tooltipPlacement }) => {
    const [{ playing, error }, play] = useSpotifyPlayer({ trackIds });

    const handleClick = (e: BaseSyntheticEvent) => {
        e.stopPropagation();
        play();
    };

    if (!trackIds.length)
        return (
            <div className={cx(CLASSNAME, { disabled: true })}>
                <GlyphIcon name="play" size={16} />
            </div>
        );

    return (
        <div
            className={cx(CLASSNAME, { playing, error })}
            data-track-id={trackIds[0]}
            role="button"
            tabIndex={0}
            onClick={handleClick}
            onKeyPress={(e) => e.key === 'Enter' && handleClick(e)}
            data-testid={TEST_ID}
        >
            {playing && <GlyphIcon name="pause" size={16} />}
            {!playing && (
                <BsOverlayTrigger
                    placement={tooltipPlacement}
                    overlay={
                        <BsTooltip id={`spotifyPlayerHint_${trackIds[0]}`}>
                            <div className={`${CLASSNAME}-hint`}>
                                <StoreIcon name="spotify" />
                                {formatMessage(TERM_PLAY_HINT)}
                            </div>
                        </BsTooltip>
                    }
                >
                    <span data-testid={TEST_CONTENT_ID}>
                        <GlyphIcon name="play" size={16} />
                    </span>
                </BsOverlayTrigger>
            )}
        </div>
    );
};

export default SpotifyPlayButton;
