import { Fragment, memo } from "@wordpress/element";
import { CheckboxControl } from "@wordpress/components";
import { decodeEntities } from "@wordpress/html-entities";

/**
 * Table row with click-to-toggle checkbox.
 * Columns: checkbox | title | URL | status.
 */
function renderHighlightedText(text, ranges, className) {
    if (!text || !Array.isArray(ranges) || ranges.length === 0) {
        return text;
    }

    const output = [];
    let cursor = 0;

    ranges.forEach(([start, end], index) => {
        const rangeStart = Math.max(0, start);
        const rangeEnd = Math.min(text.length - 1, end);

        if (rangeStart > cursor) {
            output.push(
                <Fragment key={`text-${cursor}-${rangeStart}-${index}`}>
                    {text.slice(cursor, rangeStart)}
                </Fragment>,
            );
        }

        output.push(
            <mark className={className} key={`match-${rangeStart}-${rangeEnd}-${index}`}>
                {text.slice(rangeStart, rangeEnd + 1)}
            </mark>,
        );

        cursor = rangeEnd + 1;
    });

    if (cursor < text.length) {
        output.push(
            <Fragment key={`text-tail-${cursor}`}>
                {text.slice(cursor)}
            </Fragment>,
        );
    }

    return output;
}

function PageRow({ page, isChecked, onToggle, highlights }) {
    const decodedTitle = decodeEntities(page.title || "");
    const uri = String(page.uri || "");
    const normalizedTitle = decodedTitle.trim().toLowerCase();
    const isFrontPage =
        Boolean(page.is_front_page) || normalizedTitle === "home page";

    const handleRowClick = (e) => {
        // Don't toggle if clicking interactive elements
        if (
            e.target.tagName === "INPUT" ||
            e.target.tagName === "BUTTON" ||
            e.target.tagName === "A" ||
            e.target.closest(".components-checkbox-control")
        ) {
            return;
        }
        onToggle(page.id, !isChecked);
    };

    const handleCheckboxChange = () => {
        onToggle(page.id, !isChecked);
    };

    const handleKeyDown = (e) => {
        if (e.key === "Enter" || e.key === " ") {
            e.preventDefault();
            onToggle(page.id, !isChecked);
        }
    };

    return (
        <tr
            className={isChecked ? "eci-page-row--selected" : ""}
            onClick={handleRowClick}
            onKeyDown={handleKeyDown}
            tabIndex={0}
            role="row"
        >
            <td>
                <CheckboxControl
                    checked={isChecked}
                    onChange={handleCheckboxChange}
                    __nextHasNoMarginBottom
                />
            </td>
            <td>
                <strong>
                    {renderHighlightedText(
                        decodedTitle,
                        highlights?.title,
                        "eci-search-highlight",
                    )}
                </strong>
            </td>
            <td>
                {isFrontPage ? (
                    "/"
                ) : (
                    <>
                        /
                        {renderHighlightedText(
                            uri,
                            highlights?.uri,
                            "eci-search-highlight",
                        )}
                        /
                    </>
                )}
            </td>
            <td>
                <code className={`is-post-${page.status}`}>{page.status}</code>
            </td>
        </tr>
    );
}

export default memo(PageRow);
