import { __ } from "@wordpress/i18n";
import { useRef, useEffect, useMemo } from "@wordpress/element";
import PageRow from "./PageRow";


/**
 * Custom 4-column table: checkbox | title | URL | status (no ID column).
 */
export default function PageSelectionTable({ pages, selectedIds, onToggle, allSelected, someSelected, onSelectAll, highlightByPageId }) {
    const selectAllRef = useRef(null);
    const selectedSet = useMemo(() => new Set(selectedIds), [selectedIds]);

    // Set indeterminate state on checkbox (not possible via JSX)
    useEffect(() => {
        if (selectAllRef.current) {
            selectAllRef.current.indeterminate = someSelected;
        }
    }, [someSelected]);

    if (pages.length === 0) {
        return <p>{__("No pages found on this site.", "cache-autopilot")}</p>;
    }

    const handleSelectAllChange = (e) => {
        onSelectAll(e.target.checked);
    };

    return (
        <div className='ekesto-responsive-table-container'>
            <div className='ekesto-responsive-table-inner'>
                <table className='widefat eci-table eci-page-selection-table'>
                    <thead>
                        <tr>
                            <th>
                                <input
                                    ref={selectAllRef}
                                    type='checkbox'
                                    checked={allSelected}
                                    onChange={handleSelectAllChange}
                                    title={__(
                                        "Select/deselect all visible pages",
                                        "cache-autopilot",
                                    )}
                                />
                            </th>
                            <th>{__("Page Title", "cache-autopilot")}</th>
                            <th>{__("URL", "cache-autopilot")}</th>
                            <th>{__("Status", "cache-autopilot")}</th>
                        </tr>
                    </thead>
                    <tbody>
                        {pages.map((page) => (
                            <PageRow
                                key={page.id}
                                page={page}
                                isChecked={selectedSet.has(page.id)}
                                onToggle={onToggle}
                                highlights={highlightByPageId?.get(page.id) || null}
                            />
                        ))}
                    </tbody>
                </table>
            </div>
        </div>
    );
}
