import {useEffect, useState} from "@wordpress/element";
import {__} from "@wordpress/i18n";
import Button from "../../../../../../../../button/_";
import PopupContainer from "../../../../../../../../popups/container";
import {handleError} from "../../../../../../../../../helpers/notifications";
import {DASHBOARD_CARDS_COUNT_LOCAL_KEY, DASHBOARD_CARDS_LOCAL_KEY} from "../../index";
import {GetChatbotAnalyticsTypes} from "../../../../../../../../../rest/chatbot-analytics";

const updateAllCardsCount = (count) => {
    localStorage.setItem(DASHBOARD_CARDS_COUNT_LOCAL_KEY, count || 8);
}

export default function ConfigureCardsButton({
                                                 chatbotUuid,
                                                 notifications,
                                                 updateDashboard
                                             }) {
    const [showPopup, setShowPopup] = useState(false);
    const [loading, setLoading] = useState(0);
    const [isDataFetched, setIsDataFetched] = useState(false);
    const [allCards, setAllCards] = useState([]);
    const [dashboardCards, setDashboardCards] = useState(() => {
        const cards = localStorage.getItem(DASHBOARD_CARDS_LOCAL_KEY);
        if (cards) {
            return JSON.parse(cards);
        }

        return [];
    });

    useEffect(() => {
        getAllCards();
    }, []);

    /**
     * Get all cards
     *
     * @return {Promise<void>}
     */
    const getAllCards = async () => {
        setLoading(prev => prev + 1);
        try {
            // Get all available cards (this should come from API or a constant)
            const res = await GetChatbotAnalyticsTypes(chatbotUuid);

            setAllCards(res);

            updateAllCardsCount(res?.length);
        } catch (e) {
            handleError(e, notifications.set, {
                title: __("Failed to get cards.", 'limb-chatbot'),
                description: e.message ? __(e.message, 'limb-chatbot') : __("Please check and try again.", 'limb-chatbot'),
            });
        }
        setLoading(prev => prev - 1);
        setIsDataFetched(true);
    }

    /**
     * Close popup
     */
    const closePopup = () => {
        setShowPopup(false);
    }

    const updateDashboardCards = (cards) => {
        setDashboardCards(cards);
        localStorage.setItem(DASHBOARD_CARDS_LOCAL_KEY, JSON.stringify(cards));
    }

    /**
     * Toggle card visibility
     *
     * @param {string} cardName Card name
     */
    const toggleCardVisibility = (cardName) => {
        if (!dashboardCards?.length) {
            const theRest = allCards.filter(item => item.name !== cardName).map(item => item.name);
            updateDashboardCards(theRest);
        } else {
            if (dashboardCards.includes(cardName)) {
                updateDashboardCards(dashboardCards.filter(item => item !== cardName));
            } else {
                const newCards = [...dashboardCards, cardName];
                if (allCards.every(item => newCards.includes(item.name))) {
                    updateDashboardCards([]);
                } else {
                    updateDashboardCards(newCards);
                }
            }
        }
    }

    /**
     * Check if the card is visible
     *
     * @param {string} cardName Card name
     * @return {boolean}
     */
    const isCardVisible = (cardName) => {
        return !dashboardCards.length || dashboardCards.includes(cardName);
    }

    const handleDone = async () => {
        closePopup();
        updateDashboard();
    }

    return (
        <>
            <Button
                type="secondary"
                label={__("Configure cards", 'limb-chatbot')}
                icon="settings"
                onClick={() => setShowPopup(true)}
            />
            {showPopup && (
                <PopupContainer
                    title={__("Configure dashboard cards", 'limb-chatbot')}
                    description={__("Show or hide cards", 'limb-chatbot')}
                    close={closePopup}
                    loading={loading > 0}
                    showLoadingContainer={!isDataFetched}
                    headerActions={
                        <button
                            className="lbaic-settings-popup-header-action"
                            onClick={closePopup}
                        >
                            <svg
                                className='lbaic-settings-popup-header-action-i'
                                xmlns='http://www.w3.org/2000/svg'
                                fill='none'
                                viewBox='0 0 24 24'
                            >
                                <use href='#lbaic-settings-close'/>
                            </svg>
                        </button>
                    }
                    footer={(
                        <Button
                            type="primary"
                            label={__("Done", 'limb-chatbot')}
                            onClick={handleDone}
                        />
                    )}
                >
                    <div className="lbaic-settings-dashboard-configure-cards">
                        {allCards.length > 0 ? (
                            allCards.map(card => {
                                const isVisible = isCardVisible(card.name);

                                let icon;
                                switch (card.group) {
                                    case 'builtin':
                                        icon = 'dashboard-' + card.name;
                                        break;
                                    case 'actions':
                                        icon = 'tab-actions';
                                        break;
                                    default:
                                        icon = '';
                                        break;
                                }

                                return (
                                    <button
                                        key={card.name}
                                        type="button"
                                        className="lbaic-settings-dashboard-configure-cards-item"
                                        onClick={() => toggleCardVisibility(card.name)}
                                    >
                                        <div className="lbaic-settings-dashboard-configure-cards-item-left">
                                            <svg
                                                className="lbaic-settings-dashboard-configure-cards-item-icon"
                                                xmlns="http://www.w3.org/2000/svg"
                                                fill="none"
                                                viewBox="0 0 24 24"
                                            >
                                                <use href={`#lbaic-settings-${icon}`}/>
                                            </svg>
                                            <span className="lbaic-settings-dashboard-configure-cards-item-label">
                                                {card.label}
                                            </span>
                                        </div>
                                        <svg
                                            className={`lbaic-settings-dashboard-configure-cards-item-toggle${isVisible ? ' lbaic-settings-dashboard-configure-cards-item-toggle--visible' : ''}`}
                                            xmlns="http://www.w3.org/2000/svg"
                                            fill="none"
                                            viewBox="0 0 24 24"
                                        >
                                            <use href={`#lbaic-settings-eye${isVisible ? '' : '-off'}`}/>
                                        </svg>
                                    </button>
                                );
                            })
                        ) : (
                            null
                        )}
                    </div>
                </PopupContainer>
            )}
        </>
    );
}