import {useEffect, useState} from "@wordpress/element";
import {__} from "@wordpress/i18n";
import Button from "../../../../../../../button/_";
import PopupContainer from "../../../../../../../popups/container";

export const VISITORS_COLUMNS_LOCAL_KEY = 'lbaic.settings.visitors.columns';

/**
 * Get visible column ids from localStorage. Empty = all visible.
 *
 * @param {Array} allColumns All available columns
 * @return {string[]}
 */
export const getVisibleColumns = (allColumns = []) => {
    try {
        const raw = localStorage.getItem(VISITORS_COLUMNS_LOCAL_KEY);
        const allIds = allColumns.map(c => c.id);
        if (!raw) return allIds;
        const parsed = JSON.parse(raw);
        return Array.isArray(parsed) && parsed.length ? parsed : allIds;
    } catch {
        return allColumns.map(c => c.id);
    }
};

export default function ConfigureColumnsButton({allColumns = [], onColumnsChange}) {
    const [showPopup, setShowPopup] = useState(false);
    const [visibleColumns, setVisibleColumns] = useState(() => {
        const stored = localStorage.getItem(VISITORS_COLUMNS_LOCAL_KEY);
        if (!stored) return [];
        try {
            const parsed = JSON.parse(stored);
            return Array.isArray(parsed) ? parsed : [];
        } catch {
            return [];
        }
    });

    const allColumnIds = allColumns.map(c => c.id);

    const closePopup = () => setShowPopup(false);

    useEffect(() => {
        if (showPopup) {
            try {
                const raw = localStorage.getItem(VISITORS_COLUMNS_LOCAL_KEY);
                const parsed = !raw ? [] : JSON.parse(raw);
                setVisibleColumns(Array.isArray(parsed) ? parsed : []);
            } catch {
                setVisibleColumns([]);
            }
        }
    }, [showPopup]);

    const updateStored = (ids) => {
        setVisibleColumns(ids);
        localStorage.setItem(VISITORS_COLUMNS_LOCAL_KEY, JSON.stringify(ids));
    };

    const isColumnVisible = (id) => {
        return !visibleColumns.length || visibleColumns.includes(id);
    };

    const toggleColumn = (id) => {
        if (!visibleColumns.length) {
            updateStored(allColumnIds.filter((c) => c !== id));
        } else {
            if (visibleColumns.includes(id)) {
                const next = visibleColumns.filter((c) => c !== id);
                updateStored(next.length ? next : allColumnIds);
            } else {
                const next = [...visibleColumns, id];
                updateStored(allColumnIds.every((c) => next.includes(c)) ? [] : next);
            }
        }
    };

    const handleDone = () => {
        const visible = visibleColumns.length ? visibleColumns : allColumnIds;
        closePopup();
        if (typeof onColumnsChange === 'function') {
            onColumnsChange(visible);
        }
    };

    return (
        <>
            <Button
                type="secondary"
                label={__("Configure columns", 'limb-chatbot')}
                icon="settings"
                onClick={() => setShowPopup(true)}
            />
            {showPopup && (
                <PopupContainer
                    title={__("Configure columns", 'limb-chatbot')}
                    description={__("Show or hide columns", 'limb-chatbot')}
                    close={closePopup}
                    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-leads-configure-columns">
                        {allColumns.filter(col => !col.alwaysVisible).map((col) => {
                            const isVisible = isColumnVisible(col.id);
                            return (
                                <button
                                    key={col.id}
                                    type="button"
                                    className="lbaic-settings-leads-configure-columns-item"
                                    onClick={() => toggleColumn(col.id)}
                                >
                                    <span className="lbaic-settings-leads-configure-columns-item-label">
                                        {col.label}
                                    </span>
                                    <svg
                                        className={`lbaic-settings-leads-configure-columns-item-toggle${isVisible ? ' lbaic-settings-leads-configure-columns-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>
                            );
                        })}
                    </div>
                </PopupContainer>
            )}
        </>
    );
}
