import BaseComponent from "../BaseComponent";
import { fetchData } from "../../Utils/Fetch";
import UserUtil from "../../Utils/UserUtil";
import SoundsUI from "./Sounds/SoundsUI";
import AppData from "../../Common/AppData";
import EventBus, { Events, Event } from "../../Events/EventBus";
import Player from "../../BackgroundJobs/Player";

class NewPlaylist {
    init() {
        if (!jQuery('.newplaylist-ui')[0]) {
            return;
        }
        if (jQuery('.newplaylist-ui').data('initializied') !== 'true') {
            new NewPlaylistHandler(jQuery('.newplaylist-ui'));
        }
    }
}

class NewPlaylistHandler extends BaseComponent {

    _calledInEditMode = false;
    _currentPlaylist = {};
    _isCreatingPlaylist = false;
    _existingPlaylistId = null;
    
    constructor(component_base_ui) {
        super(component_base_ui);
        this._resetPlaylistData();
        this.handleRouteChange();
        this._handleEvents();
    }

    _handleEvents() {
        const _this = this;
        const { my_playlists } = AppData.getInstance().get('routes');

        this.handlePopupClickOutside({
            newHash: `#${my_playlists?.hash}`,
        });

        this._component_base_ui.find('.playlist_name').on('keyup', (event) => {
            this._currentPlaylist.name = this._component_base_ui.find('.playlist_name').val();
            this._handleSavePlaylist();
        })

        this._component_base_ui.find('.save-playlist-btn').on('click', function(event) {
            event.preventDefault();
            _this._createPlaylist();
        })

        this._component_base_ui.find('.select-playlist-background-btn').on('click', function(event) {
            event.preventDefault();
            EventBus.getInstance().triggerEvent(Events.OPEN_SELECT_BACKGROUND_FOR_PLAYLIST, {});
        })

        this._component_base_ui.find('.clear-playlist-background-btn').on('click', function(event) {
            event.preventDefault();
            _this._clearPlaylistBackground();
        })

        const playlistBackgroundSelected = new Event(
            Events.PLAYLIST_BACKGROUND_SELECTED,
            (payload) => {
                if (payload?.backgroundId !== undefined) {
                    this._currentPlaylist.backgroundId = payload.backgroundId;
                    this._updateBackgroundButtonsVisibility();
                    console.log('Playlist background selected:', payload.backgroundId);
                }
            }
        );
        EventBus.getInstance().registerEvent(playlistBackgroundSelected);
    }

    onRouteChange(payload) {
        const { queryParams } = payload;

        this._existingPlaylistId = null;
        if (queryParams) {
            this._existingPlaylistId = queryParams.get('pid');
        }

        if (payload?.key === 'new_playlist') {
            if (!UserUtil.isLoggedIn()) {
                window.location.hash = "";
            }
            Player.getInstance().destroyAll();

            if (this._existingPlaylistId) {
                const edit_playlist_popup_title = AppData.getInstance().getLabel('edit_playlist_popup_title');
                this._component_base_ui.find('.popup-title').html(edit_playlist_popup_title);
            } else {
                const new_playlist_title = AppData.getInstance().getLabel('new_playlist_title');
                this._component_base_ui.find('.save-playlist-btn').addClass('btn-disabled');
                this._component_base_ui.find('.popup-title').html(new_playlist_title);
                this._resetPlaylistData();
            }
            this._showPopup(payload);
        } else {
            this._closePopup();
        }
    }

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

        if (!this._existingPlaylistId) {
            this._component_base_ui.find('.playlist_name').focus();
            this._component_base_ui.find('.playlist_name').val('');            
        } else {
            this._component_base_ui.find('.playlist_name').focus();
            this._component_base_ui.find('.playlist_name').val('');
            this._currentPlaylist.id = this._existingPlaylistId;
        }

        if (UserUtil.isLoggedIn()) {
            this._displaySounds();
        }
    }

    _displaySounds() {
        if (this._soundsUiInstance) {
            this._soundsUiInstance.destroyUI();
        }
        this._soundsUiInstance = new SoundsUI({
            onSelectedSounds: (soundList) => this._onSelectedSounds(),
            existingPlaylistId: this._existingPlaylistId,
            onExistingPlaylistData: (playlistData) => {
                this._component_base_ui.find('.playlist_name').val(playlistData?.name);
                this._currentPlaylist.name = playlistData?.name;
                this._currentPlaylist.backgroundId = playlistData?.backgroundId ?? -1;
                this._updateBackgroundButtonsVisibility();
                this._handleSavePlaylist();
            }
        });
        const soundsUI = this._soundsUiInstance.getComponentUI();
        this._component_base_ui.find('.content').append(soundsUI);
    }

    _onSelectedSounds() {
        this._handleSavePlaylist();
    }

    _handleSavePlaylist() {

        const playlist_name = this._component_base_ui.find('.playlist_name').val();

        const playerSounds = Player.getInstance().getPlayingSounds().map((sound) => {
            return {
                id: sound?.id,
                soundVolume: sound?.soundVolume
            }
        });

        this._currentPlaylist.sounds = playerSounds;

        if (playerSounds.length === 0) {
            return;
        }

        const { sounds, name } = this._currentPlaylist;
        if (sounds.length > 0 && name !== '') {
            this._component_base_ui.find('.save-playlist-btn').removeClass('btn-disabled');
        } else {
            this._component_base_ui.find('.save-playlist-btn').addClass('btn-disabled');
        }
    }

    _resetPlaylistData() {
        this._currentPlaylist = {
            sounds: [],
            name: '',
            backgroundId: -1
        };
        this._updateBackgroundButtonsVisibility();
    }

    _clearPlaylistBackground() {
        this._currentPlaylist.backgroundId = -1;
        this._updateBackgroundButtonsVisibility();
        console.log('Playlist background cleared');
    }

    _updateBackgroundButtonsVisibility() {
        const hasBackground = this._currentPlaylist.backgroundId !== undefined &&
                              this._currentPlaylist.backgroundId !== null &&
                              this._currentPlaylist.backgroundId !== -1 && this._currentPlaylist.backgroundId !== "-1";

        if (hasBackground) {
            this._component_base_ui.find('.select-playlist-background-btn').addClass('hidden');
            this._component_base_ui.find('.clear-playlist-background-btn').removeClass('hidden').addClass('inline-flex');
        } else {
            this._component_base_ui.find('.select-playlist-background-btn').removeClass('hidden');
            this._component_base_ui.find('.clear-playlist-background-btn').removeClass('inline-flex').addClass('hidden');
        }
    }

    async _createPlaylist() {
        const method = this._existingPlaylistId ? 'PUT' : 'POST';
        if (this._isCreatingPlaylist) {
            return;
        }
        this._isCreatingPlaylist = true;
        const result = await fetchData('playlist', method, {
            playlist: this._currentPlaylist
        });
        this._isCreatingPlaylist = false;

        if (result?.status === 200) {
            Player.getInstance().setPlaylistId(result?.data?.playlist?.id);
            const routes = AppData.getInstance().get('routes');
            window.location.hash = routes?.my_playlists.hash;
        } else {
            EventBus.getInstance().triggerEvent(Events.SHOW_FE_ERROR, { html: result?.message });
        }
    }

    _closePopup() {
        this.hide();
        this.fadeOut();
    }
}
export default NewPlaylist;