import BaseComponent from "../BaseComponent";
import UserUtil from "../../Utils/UserUtil";
import AppData from "../../Common/AppData";
import EventBus, { Events, Event } from "../../Events/EventBus";

const CanSelectStatus = {
    FREE_TO_PLAY: 'FREE_TO_PLAY',
};

class SelectBackground {
    init() {
        if (!jQuery('.backgrounds-ui')[0]) {
            return;
        }
        if (jQuery('.backgrounds-ui').data('initializied') !== 'true') {
            new SelectBackgroundHandler(jQuery('.backgrounds-ui'));
        }
    }
}

class SelectBackgroundHandler extends BaseComponent {

    _imagesBackgrounds = [];
    _videoBackgrounds = [];
    _tempSelectedBid = null;
    _isPlaylistContext = false;
    _selectedCategoryId = 'all';
    _currentBackgroundType = 'image';

    constructor(component_base_ui) {
        super(component_base_ui);
        this.handleRouteChange();
        this._handleEvents();
    }

    _handleEvents() {
        const _this = this;

        this._component_base_ui.find('.pupup-background-ui').on('click', function(event) {
            event.preventDefault();
            if (_this._isPlaylistContext) {
                _this._closePopup();
            } else {
                _this._closePopup();
                window.location.hash = '';
            }
        });

        this._component_base_ui.find('.close-btn').on('click', function(event) {
            event.preventDefault();
            if (_this._isPlaylistContext) {
                _this._closePopup();
            } else {
                window.location.hash = '';
            }
        })

        this._component_base_ui.find('.choose_img_btn').on('click', function(event) {
            event.preventDefault();
            _this._selectBackgroundType('image');
        })

        this._component_base_ui.find('.choose_video_btn').on('click', function(event) {
            event.preventDefault();
            _this._selectBackgroundType('video');
        })

        this._component_base_ui.find('.category-filter-btn').on('click', function(event) {
            event.preventDefault();
            const categoryId = jQuery(this).attr('data-category-id');
            _this._selectCategory(categoryId);
        })

        this._component_base_ui.find('.clear_btn').on('click', function(event) {
            event.preventDefault();
        })

        const openSelectBackgroundForPlaylist = new Event(
            Events.OPEN_SELECT_BACKGROUND_FOR_PLAYLIST,
            (payload) => {
                this._isPlaylistContext = true;
                this._showPopup({ key: 'select_background' });
            }
        );
        EventBus.getInstance().registerEvent(openSelectBackgroundForPlaylist);

        const closeSelectBackgroundPopup = new Event(
            Events.CLOSE_SELECT_BACKGROUND_POPUP,
            (payload) => {
                this._closePopup();
            }
        );
        EventBus.getInstance().registerEvent(closeSelectBackgroundPopup);
    }

    onRouteChange(payload) {
        if (payload?.key === 'select_background') {
            this._isPlaylistContext = false;
            this._showPopup(payload);
        } else {
            if (!this._isPlaylistContext) {
                this._closePopup();
            }
        }
    }

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

    _showBackgrounds() {
        const preloaderHtml = `<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').html(preloaderHtml);
        const allBackgrounds = AppData.getInstance().get('all_backgrounds');
        if (!Array.isArray(allBackgrounds)) {
            return;
        }

        this._imagesBackgrounds = allBackgrounds.filter(item => item.type === "image");
        this._videoBackgrounds = allBackgrounds.filter(item => item.type === "video");
        this._tempSelectedBid = null;

        // Reset category selection to "All"
        this._resetCategories();

        this._selectBackgroundType('image');
    }

    _resetCategories() {
        this._selectedCategoryId = 'all';
        this._component_base_ui.find('.category-filter-btn').removeClass('choose-background-btn-selected');
        this._component_base_ui.find('.category-all-btn').addClass('choose-background-btn-selected');
    }

    _selectBackgroundType(type = 'image') {
        this._resetCategories();
        this._currentBackgroundType = type;
        this._component_base_ui.find('.choose-bg-btn').removeClass('choose-background-btn-selected');
        switch (type) {
            case 'image':
                this._hideShowCategories(type);
                this._component_base_ui.find('.choose_img_btn').addClass('choose-background-btn-selected');
                this._renderFilteredBackgrounds();
                break;
            case 'video':
                this._hideShowCategories(type);
                this._component_base_ui.find('.choose_video_btn').addClass('choose-background-btn-selected');
                this._renderFilteredBackgrounds();
                break;
        }
    }

    _hideShowCategories(backgroundType = 'image') {
        const backgrounds = this._currentBackgroundType === 'image' ? this._imagesBackgrounds : this._videoBackgrounds;
        if (Array.isArray(backgrounds)) {
            const allCatsIds = [];
            this._component_base_ui.find('.category-filter-btn').each(function(index) {
                const catId = jQuery(this).attr('data-category-id');
                if (catId !== 'all') {
                    allCatsIds.push({catId: Number(catId), display: false});
                }
            })

            backgrounds.forEach(background => {
                const { category_id } = background;
                const foundIndex = allCatsIds.findIndex(cat => {
                    return cat?.catId === Number(category_id);
                })
                if (foundIndex !== -1) {
                    allCatsIds[foundIndex].display = true;
                }
            });


            const remainingCats = allCatsIds.filter(cat => cat?.display === true);
            if (remainingCats.length > 0) {
                this._component_base_ui.find('.category-all-btn').removeClass('hidden');
            } else {
                this._component_base_ui.find('.category-all-btn').addClass('hidden');
            }

            allCatsIds.forEach(categoryData => {
                const { catId, display } = categoryData;
                const element = jQuery(`[data-category-id="${catId}"]`);
                if (element[0]) {
                    if (display) {
                        element.removeClass('hidden');
                    } else {
                        element.addClass('hidden');
                    }
                }
            });
        }
    }

    _selectCategory(categoryId) {
        this._selectedCategoryId = categoryId;
        this._component_base_ui.find('.category-filter-btn').removeClass('choose-background-btn-selected');
        this._component_base_ui.find(`.category-filter-btn[data-category-id="${categoryId}"]`).addClass('choose-background-btn-selected');
        this._renderFilteredBackgrounds();
    }

    _renderFilteredBackgrounds() {
        const backgrounds = this._currentBackgroundType === 'image' ? this._imagesBackgrounds : this._videoBackgrounds;

        if (this._selectedCategoryId === 'all') {
            this._renderBackgrounds(backgrounds);
        } else {
            const filteredBackgrounds = backgrounds.filter(bg => {
                return bg.category_id && Number(bg.category_id) === Number(this._selectedCategoryId);
            });
            this._renderBackgrounds(filteredBackgrounds);
        }
    }

    _renderBackgrounds(backgrounds) {
        if (!Array.isArray(backgrounds)) {
            this._component_base_ui.find('.content').empty();
            return;
        }

        let allBkgsHtml = '';
        backgrounds.forEach((bkg) => {
            const { image_url_medium, type, video_icon, id } = bkg;

            const imgSrc = type === 'image' ? image_url_medium : video_icon;
            const html = `
                <div data-id="${id}" data-infostatus="" data-canselect="true" class="bg-white bg-opacity-50 cursor-pointer p-1 relative rounded-[4px] w-full sm:w-[250px] md:w-[250px] h-[200px] md:h-[180px] background-thumb">
                    <div class="relative w-full h-full rounded-[4px]" style="background-image: url('${imgSrc}');
                            background-size: cover; background-position: center; background-repeat: no-repeat;">
                    </div>
                </div>
            `;
            allBkgsHtml += html;
        })
        this._component_base_ui.find('.content').html(`
            <div class="flex flex-wrap gap-4 p-2">${allBkgsHtml}</div>
        `);
        this._addBackgroundEvents();
    }

    _addBackgroundEvents() {
        const _this = this;

        const isLoggedIn = UserUtil.isLoggedIn();
        const user_background = AppData.getInstance().get('user_background');

        this._component_base_ui.find('.background-thumb').each(function(index) {
            jQuery(this).on('click', function(event) {
                event.preventDefault();
                _this._selectBackground(jQuery(this).attr('data-id'));
            })

            if (isLoggedIn && user_background) {
                const { id } = user_background;
                if (Number(jQuery(this).attr('data-id')) === Number(id)) {
                    _this._selectBackground(jQuery(this).attr('data-id'), true);
                }
            }
        })
    }

    _selectBackground(bId, isSilent = false) {
        const _this = this;
        this._tempSelectedBid = bId;

        jQuery('.background-thumb').each(function(index) {
            if (jQuery(this).attr('data-id') === bId) {
                if (jQuery(this).hasClass('selected')) {
                    jQuery(this).removeClass('selected');
                    _this._tempSelectedBid = null;
                    if (!isSilent) {
                        if (_this._isPlaylistContext) {
                            EventBus.getInstance().triggerEvent(
                                Events.PLAYLIST_BACKGROUND_SELECTED, { backgroundId: null }
                            );
                            _this._closePopup();
                        } else {
                            EventBus.getInstance().triggerEvent(
                                Events.DEFAULT_BACKGROUND_CHANGE, { bid: _this._tempSelectedBid }
                            );
                        }
                    }
                } else {
                    jQuery(this).addClass('selected');
                    _this._tempSelectedBid = bId;
                    if (!isSilent) {
                        if (_this._isPlaylistContext) {
                            EventBus.getInstance().triggerEvent(
                                Events.PLAYLIST_BACKGROUND_SELECTED, { backgroundId: Number(bId) }
                            );
                            _this._closePopup();
                        } else {
                            EventBus.getInstance().triggerEvent(
                                Events.DEFAULT_BACKGROUND_CHANGE, { bid: _this._tempSelectedBid }
                            );
                        }
                    }
                }
            } else {
                if (jQuery(this).hasClass('selected')) {
                    jQuery(this).removeClass('selected');
                }
            }
        })
    }

    _closePopup() {
        this.hide();
        this.fadeOut();
        this._isPlaylistContext = false;
    }

}

export default SelectBackground;