import type { FC } from 'react';
import React, { useCallback, useEffect, useState } from 'react';
import { BsOverlayTrigger, BsTooltip, CoverArt } from '@theorchard/suite-components';
import { formatMessage } from '@theorchard/suite-i18n';
import { GlyphIcon } from '@theorchard/suite-icons';
import cx from 'classnames';
import SpotifyWebApiInstance from './spotifyWebApi';

export const CLASSNAME = 'SpotifyPlayer';
const CLASSNAME_BODY = `${CLASSNAME}-body`;
const CLASSNAME_TITLE = `${CLASSNAME}-title`;
const CLASSNAME_ARTISTS = `${CLASSNAME}-artists`;
const CLASSNAME_CONTROLS = `${CLASSNAME}-controls`;
const CLASSNAME_PLAY_BTN = `${CLASSNAME}-play-btn`;
const CLASSNAME_CLOSE_BTN = `${CLASSNAME}-close-btn`;

export const TEST_ID = CLASSNAME;
export const TERM_CLOSE = 'spotifyPlayer.close';

const SpotifyPlayer: FC = () => {
    const [currentTrack, setCurrentTrack] = useState<Spotify.PlayerTrack | undefined>();
    const [playing, setPlaying] = useState(false);
    const [visible, setVisible] = useState(true);

    const handleStateChange = useCallback((event: Spotify.PlayerState | null) => {
        setCurrentTrack(event?.track_window.current_track);
        setPlaying(!!event && !event.paused);
    }, []);

    useEffect(() => {
        const { player } = SpotifyWebApiInstance;
        void player?.getCurrentState().then(handleStateChange);
        player?.addListener('player_state_changed', handleStateChange);
        return () => player?.removeListener('player_state_changed', handleStateChange);
    }, [handleStateChange]);

    useEffect(() => {
        if (playing) setVisible(true);
    }, [playing]);

    const handleClick = () => {
        const { player } = SpotifyWebApiInstance;
        player?.togglePlay();
    };

    const handleClose = () => {
        const { player } = SpotifyWebApiInstance;
        if (playing) player?.togglePlay();
        setVisible(false);
    };

    if (!visible) return null;

    return (
        <div className={cx(CLASSNAME, { ready: !!currentTrack })} data-testid={TEST_ID}>
            <a
                target="_blank"
                rel="noreferrer"
                href={`https://open.spotify.com/track/${currentTrack?.id}`}
            >
                <CoverArt width="50" url={currentTrack?.album.images[0].url} />
            </a>
            <div className={CLASSNAME_BODY}>
                <div className={CLASSNAME_TITLE}>{currentTrack?.name}</div>
                <div className={CLASSNAME_ARTISTS}>
                    {currentTrack?.artists.map((artist) => artist.name).join(', ')}
                </div>
            </div>
            <div className={CLASSNAME_CONTROLS}>
                <div
                    role="button"
                    tabIndex={0}
                    className={CLASSNAME_PLAY_BTN}
                    onClick={handleClick}
                    onKeyPress={(e) => e.key === 'Enter' && handleClick()}
                >
                    {playing && <GlyphIcon name="pause" size={16} />}
                    {!playing && <GlyphIcon name="play" size={16} />}
                </div>

                <BsOverlayTrigger
                    overlay={
                        <BsTooltip id="spotifyPlayerClose">{formatMessage(TERM_CLOSE)}</BsTooltip>
                    }
                >
                    <div
                        role="button"
                        tabIndex={0}
                        className={CLASSNAME_CLOSE_BTN}
                        onClick={handleClose}
                        onKeyPress={(e) => e.key === 'Enter' && handleClose()}
                    >
                        <GlyphIcon name="close" size={12} />
                    </div>
                </BsOverlayTrigger>
            </div>
        </div>
    );
};

export default SpotifyPlayer;
