const { __ } = wp.i18n;

import { isPremiumUser } from '../utils/premium';

class SharedLinkSelector {
    constructor(store) {
        this.store = store;
        this.selectedLinkId = null;
        this.selectedLinkTitle = null;
        this.selectedCategoryId = null;
        this.selectedCategoryName = null;
        this.isPremium = isPremiumUser();
    }

    init() {
        this.setupEventListeners();
        this.updateAllLinksButtonState(true);
    }

    setupEventListeners() {
        jQuery('#linkcentral-shared-all-links').on('click', (e) => {
            e.preventDefault();
            this.resetToAllLinks();
        });

        
    }

    handleUnifiedSelect(event, ui) {
        if (ui.item.type === 'link') {
            this.selectedLinkId = ui.item.value;
            this.selectedLinkTitle = ui.item.title;
            this.selectedCategoryId = null;
            this.selectedCategoryName = null;
        } else if (ui.item.type === 'category') {
            this.selectedCategoryId = ui.item.value;
            this.selectedCategoryName = ui.item.title;
            this.selectedLinkId = null;
            this.selectedLinkTitle = null;
        }

        jQuery('#linkcentral-shared-unified-search').val(ui.item.title);
        this.updateAllLinksButtonState(false);
        this.publishSelection();
        return false;
    }

    resetToAllLinks() {
        this.selectedLinkId = null;
        this.selectedLinkTitle = null;
        this.selectedCategoryId = null;
        this.selectedCategoryName = null;
        jQuery('#linkcentral-shared-unified-search').val('');
        this.updateAllLinksButtonState(true);
        this.publishSelection();
    }

    updateAllLinksButtonState(isAllLinksSelected) {
        jQuery('#linkcentral-shared-all-links').toggleClass('selected', isAllLinksSelected);
        jQuery('#linkcentral-shared-unified-search').toggleClass(
            'linkcentral-has-selection',
            !isAllLinksSelected
        );
    }

    selectLink(linkId, linkTitle) {
        this.selectedLinkId = linkId;
        this.selectedLinkTitle = linkTitle;
        this.selectedCategoryId = null;
        this.selectedCategoryName = null;

        const $search = jQuery('#linkcentral-shared-unified-search');
        if ($search.length) {
            $search.val(linkTitle || '');
        }

        this.updateAllLinksButtonState(false);
        this.publishSelection();
    }

    publishSelection() {
        if (typeof this.store.setLinkSelection !== 'function') {
            return;
        }

        this.store.setLinkSelection({
            linkId: this.selectedLinkId,
            categoryId: this.selectedCategoryId,
        });
    }

    

    getCurrentSelection() {
        return {
            linkId: this.selectedLinkId,
            linkTitle: this.selectedLinkTitle,
            categoryId: this.selectedCategoryId,
            categoryName: this.selectedCategoryName,
        };
    }
}

export default SharedLinkSelector;
