import { useState, useEffect, useRef, useMemo } from "@wordpress/element";
import { __, sprintf } from "@wordpress/i18n";
import { useDispatch } from "@wordpress/data";
import { store as noticesStore } from "@wordpress/notices";
import { Spinner, Button, Icon } from "@wordpress/components";
import { check, cancelCircleFilled as errorIcon } from "@wordpress/icons";
import CustomSection from "../components/CustomSection";
import PostTypePills from "../components/PostTypePills";
import PriorityPageSelector from "../components/PriorityPageSelector";
import { fuzzySearchPages } from "../utils/fuzzyPageSearch";

const CACHE_WARMUP_DOCS_URL = "https://wpcacheautopilot.com/docs/cache-warmup/";
const PRIORITIES_PANEL_HELP_URLS = {
    warmupPriorities: `${CACHE_WARMUP_DOCS_URL}#warmup-priorities`,
    priorityPages: `${CACHE_WARMUP_DOCS_URL}#priority-pages`,
};

export default function PrioritiesTab({
    options,
    setOptions,
    sitemapStatus,
    priorityPages,
    priorityPagesLoading,
    priorityPagesError,
    onRefreshSitemapStatus,
    onRefreshPriorityPages,
}) {
    const priorities = options.priorities || {};
    const [searchTerm, setSearchTerm] = useState("");
    const searchInputRef = useRef(null);
    const [isRefreshingSitemap, setIsRefreshingSitemap] = useState(false);
    const [isRefreshingPages, setIsRefreshingPages] = useState(false);
    const [refreshError, setRefreshError] = useState(null);
    const { createSuccessNotice, createErrorNotice } = useDispatch(noticesStore);

    const pages = Array.isArray(priorityPages)
        ? priorityPages.filter((page) => page?.is_front_page !== true)
        : [];
    const postTypes = Array.isArray(sitemapStatus?.post_types) ? sitemapStatus.post_types : [];
    const hasSitemap = typeof sitemapStatus?.has_sitemap === "boolean"
        ? sitemapStatus.has_sitemap
        : true;
    const statusMessage = sitemapStatus?.status_message || "";
    const generatedAt = sitemapStatus?.generated_at || null;
    const lastError = refreshError || sitemapStatus?.last_error || null;

    const handleRefreshSitemap = async () => {
        if (typeof onRefreshSitemapStatus !== "function") {
            return;
        }

        setIsRefreshingSitemap(true);
        setRefreshError(null);
        try {
            await onRefreshSitemapStatus();
            createSuccessNotice(__("Sitemap data refreshed.", "cache-autopilot"), {
                type: "snackbar",
                icon: <Icon icon={check} />,
            });
        } catch (err) {
            const errorMessage = err?.message || __("Failed to refresh sitemap data.", "cache-autopilot");
            setRefreshError(errorMessage);
            createErrorNotice(errorMessage, {
                type: "snackbar",
                icon: <Icon icon={errorIcon} />,
            });
            console.error(err);
        } finally {
            setIsRefreshingSitemap(false);
        }
    };

    const handleRefreshPages = async () => {
        if (typeof onRefreshPriorityPages !== "function") {
            return;
        }

        setIsRefreshingPages(true);
        try {
            await onRefreshPriorityPages();
            createSuccessNotice(__("Page list reloaded.", "cache-autopilot"), {
                type: "snackbar",
                icon: <Icon icon={check} />,
            });
        } catch (err) {
            createErrorNotice(
                err?.message || __("Failed to reload page list.", "cache-autopilot"),
                {
                    type: "snackbar",
                    icon: <Icon icon={errorIcon} />,
                },
            );
            console.error(err);
        } finally {
            setIsRefreshingPages(false);
        }
    };

    const formattedGeneratedAt = generatedAt
        ? new Date(generatedAt).toLocaleString()
        : null;
    const hasSnapshot = !!generatedAt;
    const hasDetectedPostTypes = postTypes.length > 0;
    const isOutdatedStatus = statusMessage.toLowerCase().includes("outdated");

    const updateField = (field, value) => {
        setOptions({
            ...options,
            priorities: { ...priorities, [field]: value },
        });
    };

    // Keyboard shortcut: Shift+F focuses search input
    useEffect(() => {
        const handleKeyDown = (e) => {
            if (e.shiftKey && e.key === "F") {
                e.preventDefault();
                if (searchInputRef.current) {
                    searchInputRef.current.focus();
                    searchInputRef.current.select();
                }
            }
        };

        document.addEventListener("keydown", handleKeyDown);
        return () => document.removeEventListener("keydown", handleKeyDown);
    }, []);

    const filteredPageRows = useMemo(
        () => fuzzySearchPages(pages, searchTerm),
        [pages, searchTerm],
    );

    const filteredPages = useMemo(
        () => filteredPageRows.map(({ page }) => page),
        [filteredPageRows],
    );

    const highlightsByPageId = useMemo(() => {
        const map = new Map();
        filteredPageRows.forEach(({ page, highlights }) => {
            if (highlights) {
                map.set(page.id, highlights);
            }
        });
        return map;
    }, [filteredPageRows]);

    // Calculate selection state for visible (filtered) pages
    const selectedPageIds = priorities.priority_pages || [];
    const selectedPageIdSet = useMemo(
        () => new Set(selectedPageIds),
        [selectedPageIds],
    );
    const visibleIds = useMemo(
        () => filteredPages.map((page) => page.id),
        [filteredPages],
    );
    const visibleIdSet = useMemo(
        () => new Set(visibleIds),
        [visibleIds],
    );
    const visibleSelectedCount = useMemo(
        () => visibleIds.reduce(
            (count, id) => count + (selectedPageIdSet.has(id) ? 1 : 0),
            0,
        ),
        [visibleIds, selectedPageIdSet],
    );
    const allSelected = visibleIds.length > 0 && visibleSelectedCount === visibleIds.length;
    const someSelected = visibleSelectedCount > 0 && visibleSelectedCount < visibleIds.length;

    const handleSelectAll = (isChecked) => {
        const currentIds = priorities.priority_pages || [];
        let newIds;

        if (isChecked) {
            // Select all visible pages
            newIds = [...new Set([...currentIds, ...visibleIds])];
        } else {
            // Deselect all visible pages
            newIds = currentIds.filter((id) => !visibleIdSet.has(id));
        }

        updateField("priority_pages", newIds);
    };

    if (priorityPagesLoading && pages.length === 0) {
        return (
            <div style={{ padding: "20px", textAlign: "center" }}>
                <Spinner />
            </div>
        );
    }

    return (
        <>
            <CustomSection
                title={__("Warmup Priorities", "cache-autopilot")}
                helpUrl={PRIORITIES_PANEL_HELP_URLS.warmupPriorities}
            >
                <p className='ekesto-section-description'>
                    {!hasSitemap
                        ? __(
                              "No sitemap configured. Warmup falls back to published pages.",
                              "cache-autopilot",
                          )
                        : hasDetectedPostTypes
                        ? __(
                              "In a full warmup, URLs are warmed in this order, after priority pages. Drag to reorder.",
                              "cache-autopilot",
                          )
                        : !hasSnapshot
                        ? __(
                              "First-time setup: click Refresh sitemap data to load post types.",
                              "cache-autopilot",
                          )
                        : __(
                              "No post types found in your sitemap. Check sitemap content, then refresh.",
                              "cache-autopilot",
                          )}
                </p>
                {hasSitemap && (
                    <div className='ecw-manual-run'>
                        <Button
                            variant='secondary'
                            className='ecw-manual-run__button'
                            onClick={handleRefreshSitemap}
                            isBusy={isRefreshingSitemap}
                            disabled={isRefreshingSitemap}
                        >
                            {__("Refresh sitemap data", "cache-autopilot")}
                        </Button>
                        {hasDetectedPostTypes && (
                            <p className='ekesto-section-description ecw-manual-run__description'>
                                {__(
                                    "Update this list when post types were added, removed, or sitemap settings changed.",
                                    "cache-autopilot",
                                )}
                            </p>
                        )}
                        {hasDetectedPostTypes && isOutdatedStatus && (
                            <p className='ecw-helper-text'>{statusMessage}</p>
                        )}
                        {hasDetectedPostTypes && formattedGeneratedAt && (
                            <p className='ecw-helper-text'>
                                {sprintf(
                                    __("Last refreshed: %s", "cache-autopilot"),
                                    formattedGeneratedAt,
                                )}
                            </p>
                        )}
                        {lastError && (
                            <p className='ecw-helper-text'>{lastError}</p>
                        )}
                    </div>
                )}

                {hasSitemap && hasDetectedPostTypes && (
                    <PostTypePills
                        postTypes={postTypes}
                        orderedPostTypes={priorities.post_type_order || []}
                        onChange={(newOrder) =>
                            updateField("post_type_order", newOrder)
                        }
                    />
                )}

                {hasSitemap && hasDetectedPostTypes && (
                    <p className='ecw-helper-text'>
                        {__(
                            "Missing a post type? Check your SEO plugin's sitemap settings.",
                            "cache-autopilot",
                        )}
                    </p>
                )}
            </CustomSection>

            <CustomSection
                title={__("Priority Pages", "cache-autopilot")}
                helpUrl={PRIORITIES_PANEL_HELP_URLS.priorityPages}
            >
                <p className='ekesto-section-description'>
                    {__(
                        "The front page is always warmed first and is not listed here.",
                        "cache-autopilot",
                    )}
                </p>
                <div className='ekesto-search-container'>
                    <input
                        ref={searchInputRef}
                        type='text'
                        className='ekesto-search-container__input'
                        placeholder={__("Search (Shift + F)", "cache-autopilot")}
                        value={searchTerm}
                        onChange={(e) => setSearchTerm(e.target.value)}
                    />
                </div>
                {typeof onRefreshPriorityPages === "function" && (
                    <div className='ecw-manual-run'>
                        <Button
                            variant='secondary'
                            className='ecw-manual-run__button'
                            onClick={handleRefreshPages}
                            isBusy={isRefreshingPages}
                            disabled={isRefreshingPages}
                        >
                            {__("Reload page list", "cache-autopilot")}
                        </Button>
                    </div>
                )}
                {priorityPagesError && (
                    <p className='ecw-helper-text'>{priorityPagesError}</p>
                )}
                <PriorityPageSelector
                    pages={filteredPages}
                    selectedPageIds={selectedPageIds}
                    selectedPageIdSet={selectedPageIdSet}
                    onChange={(newIds) => updateField("priority_pages", newIds)}
                    allSelected={allSelected}
                    someSelected={someSelected}
                    onSelectAll={handleSelectAll}
                    highlightByPageId={highlightsByPageId}
                />
            </CustomSection>
        </>
    );
}
