import BaseComponent from "../BaseComponent";
import { fetchData } from "../../Utils/Fetch";
import UserUtil from "../../Utils/UserUtil";
import SoundsUI from "./Sounds/SoundsUI";
import PlaylistUI from "./PlaylistUI";
import AppData from "../../Common/AppData";
import PlaylistUtils from "../../Utils/PlaylistUtils";

class MyPlaylists {
    init() {
        if (!jQuery('.playlists-ui')[0]) {
            return;
        }
        if (jQuery('.playlists-ui').data('initializied') !== 'true') {
            new MyPlaylistsHandler(jQuery('.playlists-ui'));
        }
    }
}

class MyPlaylistsHandler extends BaseComponent {

    _soundsUiInstance = null;
    _allSounds = [];
    _playlistsUIInstances = [];

    constructor(component_base_ui) {

        super(component_base_ui);
        this.handleRouteChange();
        this._handleEvents();

        const soundsCollections = AppData.getInstance().get('sounds_collections');
        if (Array.isArray(soundsCollections)) {
            this._allSounds = soundsCollections.flatMap(playlist => playlist.sounds);
        }
    }

    _handleEvents() {
        this.handlePopupClickOutside({
            newHash: '',
        });
    }

    onRouteChange(payload) {
        if (payload?.key === 'my_playlists') {
            this._showPopup(payload);
        } else {
            this._closePopup();
        }
    }

    _showPopup(payload) {
        document.title = payload?.data?.page_title ?? '';
        this.show();
        this.fadeIn();

        if (UserUtil.isLoggedIn()) {
            this._handleResetView();
            this._fetchUserPlaylists();
        } else {
            this._displaySounds();
        }
    }

    _closePopup() {
        this.hide();
        this.fadeOut();
    }

    _handleResetView() {
        this._component_base_ui.find('.content').empty();
        this._component_base_ui.find('.errors').addClass('hidden');
        this._component_base_ui.find('.errors p').addClass('hidden');
    }

    _fetchUserPlaylists() {
        this._component_base_ui.find('.errors p').addClass('hidden');
        this._component_base_ui.find('.errors').removeClass('hidden');
        this._component_base_ui.find('.content').empty();
        this._getPlaylists();
    }

    async _getPlaylists() {
        this._component_base_ui.find('.errors p').addClass('hidden');
        this._component_base_ui.find('.errors').removeClass('hidden');

        const preloaderUI = jQuery(`<div class="loading-ripples flex items-center justify-center"><div class="lds-ripple"><div></div><div></div></div></div>`);
        this._component_base_ui.find('.content').empty();
        preloaderUI.appendTo(this._component_base_ui.find('.content'));

        const sanitizedPlaylists = await PlaylistUtils.getSanitizedPlaylists();

        setTimeout(() => {
            this._component_base_ui.find('.content').empty();
            this._renderPlaylists(sanitizedPlaylists);
        }, 300)
    }

    _renderPlaylists(playlists) {
        if (playlists.length === 0) {
            this._component_base_ui.find('.errors .no-playlists').removeClass('hidden');
            return;
        }

        this._playlistsUIInstances.forEach((instance) => {
            instance.gcc();
        });
        this._playlistsUIInstances = [];

        playlists.forEach(playlist => {
            const { name } = playlist;

            const edit_playlist = AppData.getInstance().getLabel('edit_playlist');
            const remove_playlist = AppData.getInstance().getLabel('remove_playlist');

            const playlistHtml = `
                <div class="my-6 mt-2 mr-3 bg-white bg-opacity-30 text-white text-sm rounded-full pl-7 pr-10 py-3 transition duration-200 
                            hover:bg-opacity-50 disabled:bg-opacity-20 disabled:cursor-not-allowed 
                            inline-flex items-center gap-2 relative cursor-pointer playlist-list-btn">
                    ${ name }
                    <a class="absolute left-[0.125rem] top-1/2 -translate-y-1/2 hidden play-indicator">
                        <svg width="24" height="24" viewBox="0 0 64 64" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path d="M16 24H24L32 16V48L24 40H16V24Z" fill="white"/>
                        <path d="M40 24C42.2091 24 44 25.7909 44 28V36C44 38.2091 42.2091 40 40 40" stroke="white" stroke-width="2" stroke-linecap="round"/>
                        <path d="M44 20C47.3137 20 50 22.6863 50 26V38C50 41.3137 47.3137 44 44 44" stroke="white" stroke-width="2" stroke-linecap="round"/>
                        </svg>
                    </a>
                    <a class="absolute right-3 top-1/2 -translate-y-1/2 px-0.5 py-1 cursor-pointer playlist-options-btn">
                        <svg xmlns="http://www.w3.org/2000/svg" fill="currentColor" viewBox="0 0 28 28" class="w-4 h-4">
                            <circle cx="12" cy="5" r="3"></circle>
                            <circle cx="12" cy="15" r="3"></circle>
                            <circle cx="12" cy="25" r="3"></circle>
                        </svg>
                    </a>
                        <div class="absolute right-0 top-0 -translate-y-full translate-x-full top-full mt-1 w-24 bg-white text-black rounded-lg shadow-lg 
                                        playlist-menu z-50 
                                        before:content-[''] before:absolute before:left-0 before:top-1/2 before:-translate-x-full before:-translate-y-1/2 
                                        before:border-[5px] before:border-transparent before:border-r-white hidden playlist-options">
                            <button class="block w-full text-left px-3 py-1 hover:bg-gray-100 rounded-t-lg edit-playlist">${edit_playlist}</button>
                            <button class="block w-full text-left px-3 py-1 hover:bg-gray-100 rounded-b-lg remove-playlist">${remove_playlist}</button>
                        </div>
                </div>
            `;
            const playlistUI = jQuery(playlistHtml);
            playlistUI.appendTo(this._component_base_ui.find('.content'));
            const instance = new PlaylistUI(playlistUI, playlist);
            this._playlistsUIInstances.push(instance);
        });
    }

    _displaySounds() {
        this._component_base_ui.find('.errors p').addClass('hidden');
        this._component_base_ui.find('.errors').removeClass('hidden');
        this._component_base_ui.find('.errors .playlist-create-restriction').removeClass('hidden');
        this._component_base_ui.find('.new-playlist-btn').addClass('btn-disabled');
        if (this._soundsUiInstance) {
            return;
        }
        this._soundsUiInstance = new SoundsUI();
        const soundsUI = this._soundsUiInstance.getComponentUI();
        this._component_base_ui.find('.content').append(soundsUI);
    }

}

export default MyPlaylists;