import {useEffect, useState} from "@wordpress/element";
import {__, sprintf} from "@wordpress/i18n";
import PopupContainer from "../../../../../../../popups/container";
import Button from "../../../../../../../button/_";
import Checkbox from "../../../../../../../fields/checkbox";
import confirm from "../../../../../../../../helpers/confirm";

/**
 * Sitemap Links Popup
 * Displays links fetched from sitemap and allows user to proceed with learning
 */
export default function SitemapLinksPopup({
                                              close,
                                              sitemapUrls,
                                              onDeleteUrl,
                                              isJobRunning,
                                              jobProgress,
                                              jobError,
                                              onLearn,
                                              notifications
                                          }) {
    const [urls, setUrls] = useState([]);
    const [selectedUrls, setSelectedUrls] = useState([]);

    useEffect(() => {
        setUrls(sitemapUrls || []);
        // Clear selection when URLs change
        setSelectedUrls([]);
    }, [sitemapUrls]);

    /**
     * Handle close with confirmation
     */
    const handleClose = async () => {
        if (await confirm(__("Are you sure you want to close? This will cancel the current operation.", 'limb-chatbot'))) {
            close();
        }
    };

    /**
     * Toggle URL selection
     */
    const toggleUrlSelection = (index, event) => {
        // Prevent toggle if clicking on delete button
        if (event?.target?.closest('.lbaic-settings-sitemap-links-item-delete')) {
            return;
        }

        setSelectedUrls(prev => {
            if (prev.includes(index)) {
                return prev.filter(i => i !== index);
            } else {
                return [...prev, index];
            }
        });
    };

    /**
     * Handle delete individual URL
     */
    const handleDeleteUrl = async (url, index, event) => {
        event?.stopPropagation();
        
        if (await confirm(__("Are you sure you want to remove this URL from the list?", 'limb-chatbot'))) {
            const newUrls = urls.filter((_, i) => i !== index);
            setUrls(newUrls);
            setSelectedUrls(prev => prev.filter(i => i !== index).map(i => i > index ? i - 1 : i));
            if (onDeleteUrl) {
                onDeleteUrl(newUrls);
            }
        }
    };

    /**
     * Toggle select all URLs
     */
    const toggleSelectAll = () => {
        if (selectedUrls.length === urls.length) {
            setSelectedUrls([]);
        } else {
            setSelectedUrls(urls.map((_, index) => index));
        }
    };

    /**
     * Handle delete selected URLs
     */
    const handleDeleteSelected = async () => {
        if (selectedUrls.length === 0) {
            return;
        }

        const count = selectedUrls.length;
        const message = count === 1
            ? __("Are you sure you want to remove this URL from the list?", 'limb-chatbot')
            : sprintf(__("Are you sure you want to remove %d URLs from the list?", 'limb-chatbot'), count);

        if (await confirm(message)) {
            const newUrls = urls.filter((_, index) => !selectedUrls.includes(index));
            setUrls(newUrls);
            setSelectedUrls([]);
            if (onDeleteUrl) {
                onDeleteUrl(newUrls);
            }
        }
    };

    /**
     * Handle learn button click
     */
    const handleLearn = () => {
        if (onLearn && selectedUrls.length > 0) {
            // Get only selected URLs
            const selectedUrlsList = urls.filter((_, index) => selectedUrls.includes(index));
            onLearn(selectedUrlsList);
        }
    };

    const showNoLinks = !isJobRunning && (jobProgress > 0 || jobError) && urls.length === 0;
    const showFooterButtons = !isJobRunning && urls.length > 0;
    const isAllSelected = selectedUrls.length === urls.length && urls.length > 0;
    const isPartiallySelected = selectedUrls.length > 0 && selectedUrls.length < urls.length;
    const hasSelection = selectedUrls.length > 0;

    // Generate count label
    const getCountLabel = () => {
        if (selectedUrls.length === 0) {
            return sprintf(__("%d links", 'limb-chatbot'), urls.length);
        } else if (isAllSelected) {
            return sprintf(__("All %d selected", 'limb-chatbot'), urls.length);
        } else {
            return sprintf(__("%d of %d selected", 'limb-chatbot'), selectedUrls.length, urls.length);
        }
    };

    return (
        <PopupContainer
            title={__("Links", 'limb-chatbot')}
            description={__("Select links to learn", 'limb-chatbot')}
            close={handleClose}
            loading={isJobRunning}
            popupClassName="lbaic-settings-popup-sitemap-links"
            headerActions={
                <button
                    className="lbaic-settings-popup-header-action"
                    onClick={handleClose}
                >
                    <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={
                showFooterButtons ? (
                    <>
                        <Button
                            type="danger"
                            label={__("Delete", 'limb-chatbot')}
                            icon="delete"
                            onClick={handleDeleteSelected}
                            disabled={!hasSelection}
                            className="lbaic-settings-popup-footer-button"
                        />
                        <Button
                            type="primary"
                            label={__("Learn", 'limb-chatbot')}
                            icon="run"
                            onClick={handleLearn}
                            disabled={!hasSelection}
                            className="lbaic-settings-popup-footer-button"
                        />
                    </>
                ) : null
            }
        >
            <div className="lbaic-settings-sitemap-links">
                {urls.length > 0 && (
                    <div className="lbaic-settings-sitemap-links-header">
                        <div className="lbaic-settings-sitemap-links-header-left">
                            <Checkbox
                                isChecked={isAllSelected}
                                isIntermediateChecked={isPartiallySelected}
                                toggleValue={toggleSelectAll}
                            />
                            <span className="lbaic-settings-sitemap-links-count">
                                {getCountLabel()}
                            </span>
                        </div>
                    </div>
                )}

                {showNoLinks && (
                    <div className="lbaic-settings-sitemap-links-empty">
                        <p>{__("No links found", 'limb-chatbot')}</p>
                    </div>
                )}

                {urls.length > 0 && (
                    <div className="lbaic-settings-sitemap-links-list">
                        {urls.map((url, index) => (
                            <div 
                                key={index} 
                                className={`lbaic-settings-sitemap-links-item${selectedUrls.includes(index) ? ' selected' : ''}`}
                                onClick={(e) => toggleUrlSelection(index, e)}
                            >
                                <Checkbox
                                    isChecked={selectedUrls.includes(index)}
                                    toggleValue={(e) => toggleUrlSelection(index, e)}
                                />
                                <span className="lbaic-settings-sitemap-links-item-url" title={url}>
                                    {url}
                                </span>
                                <button
                                    className="lbaic-settings-sitemap-links-item-delete"
                                    onClick={(e) => handleDeleteUrl(url, index, e)}
                                    disabled={isJobRunning}
                                    title={__("Remove", 'limb-chatbot')}
                                >
                                    <svg
                                        className="lbaic-settings-sitemap-links-item-delete-icon"
                                        xmlns="http://www.w3.org/2000/svg"
                                        fill="none"
                                        viewBox="0 0 24 24"
                                    >
                                        <use href="#lbaic-settings-delete"></use>
                                    </svg>
                                </button>
                            </div>
                        ))}
                    </div>
                )}
            </div>
        </PopupContainer>
    );
}
