import { memo } from "@wordpress/element";
import { Notice } from "@wordpress/components";
import { __, sprintf } from "@wordpress/i18n";
import { decodeEntities } from "@wordpress/html-entities";


const PREVIEW_LIMIT = 10;

function normalizePageId(value) {
    const parsed = Number.parseInt(value, 10);
    return Number.isFinite(parsed) && parsed > 0 ? parsed : null;
}

function normalizePageIdList(values) {
    if (!Array.isArray(values)) {
        return [];
    }

    const seen = new Set();
    values.forEach((value) => {
        const normalized = normalizePageId(value);
        if (normalized !== null) {
            seen.add(normalized);
        }
    });

    return [...seen];
}

function getPageTitle(title) {
    if (typeof title === "string") {
        return title;
    }

    if (
        title &&
        typeof title === "object" &&
        typeof title.rendered === "string"
    ) {
        return title.rendered;
    }

    return "";
}

function SelectedPagesSummary({ selectedIds, availablePages, isTruncated = false }) {
    const ids = normalizePageIdList(selectedIds);
    const pageMap = new Map(
        (availablePages || [])
            .map((page) => {
                const pageId = normalizePageId(page?.id);
                return pageId === null ? null : [pageId, page];
            })
            .filter(Boolean),
    );
    const previewRows = ids
        .map((id) => pageMap.get(id))
        .filter(Boolean)
        .slice(0, PREVIEW_LIMIT);
    const unresolvedCount = ids.filter((id) => !pageMap.has(id)).length;

    return (
        <div className='eci-selected-pages-summary'>
            <p className='ekesto-section-description is-italic is-small mt-md mb-sm'>
                {ids.length === 0
                    ? __("No pages selected yet.", "cache-autopilot")
                    : `${ids.length} ${__("page(s) selected.", "cache-autopilot")}`}
            </p>

            {previewRows.length > 0 && (
                <div className='ekesto-responsive-table-container'>
                    <div className='ekesto-responsive-table-inner'>
                        <table className='widefat eci-table eci-page-selection-table eci-page-selection-table--summary'>
                            <thead>
                                <tr>
                                    <th>{__("Page Title", "cache-autopilot")}</th>
                                    <th>{__("URL", "cache-autopilot")}</th>
                                    <th>{__("Status", "cache-autopilot")}</th>
                                </tr>
                            </thead>
                            <tbody>
                                {previewRows.map((page) => {
                                    const decodedTitle = decodeEntities(
                                        getPageTitle(page.title),
                                    );
                                    const normalizedTitle = decodedTitle
                                        .trim()
                                        .toLowerCase();
                                    const isFrontPage =
                                        Boolean(page.is_front_page) ||
                                        normalizedTitle === "home page";
                                    const displayedUrl = isFrontPage
                                        ? "/"
                                        : `/${page.uri}`;

                                    return (
                                        <tr key={page.id}>
                                            <td>
                                                <strong>{decodedTitle}</strong>
                                            </td>
                                            <td>{displayedUrl}</td>
                                            <td>
                                                <code
                                                    className={`is-post-${page.status}`}
                                                >
                                                    {page.status}
                                                </code>
                                            </td>
                                        </tr>
                                    );
                                })}
                            </tbody>
                        </table>
                    </div>
                </div>
            )}

            {ids.length > PREVIEW_LIMIT && (
                <p className='ekesto-section-description is-small is-italic mt-sm'>
                    {sprintf(
                        __(
                            "Showing first %d selected pages. Open selector to review all.",
                            "cache-autopilot",
                        ),
                        PREVIEW_LIMIT,
                    )}
                </p>
            )}

            {unresolvedCount > 0 && (
                <Notice
                    status='warning'
                    isDismissible={false}
                    className='mt-sm'
                >
                    {isTruncated
                        ? __(
                              "Some selected pages are outside the loaded selector list and cannot be previewed here.",
                              "cache-autopilot",
                          )
                        : __(
                              "Some selected pages are no longer available. Open selector and save to remove them.",
                              "cache-autopilot",
                          )}
                </Notice>
            )}
        </div>
    );
}

export default memo(SelectedPagesSummary);
