import { __, sprintf } from "@wordpress/i18n";
import { Notice } from "@wordpress/components";
import SimpleModePanel from "../components/SimpleModePanel";
import CustomSection from "../components/CustomSection";
import {
    NextToggleControl,
    NextNumberControl,
} from "../components/NextControls";

import SupportDebugPanel from "../components/SupportDebugPanel";
import {
    AccessControlSlot,
    MultilingualFanoutSlot,
    TimedInvalidationSlot,
} from "@cache-autopilot/invalidator-settings-feature-panels";

const CACHE_INVALIDATOR_DOCS_URL =
    "https://wpcacheautopilot.com/docs/cache-invalidator/";

const SETTINGS_PANEL_HELP_URLS = {
    general: `${CACHE_INVALIDATOR_DOCS_URL}#general`,
    groupManagement: `${CACHE_INVALIDATOR_DOCS_URL}#post-type-tabs`,
    themeArchiveChanges: `${CACHE_INVALIDATOR_DOCS_URL}#theme-archive-changes`,
    invalidationBehavior: `${CACHE_INVALIDATOR_DOCS_URL}#invalidation-behavior`,
    supportDebugging: `${CACHE_INVALIDATOR_DOCS_URL}#support-debug-mode`,
};

/**
 * Settings tab container with global and post type tab controls.
 */
export default function SettingsTab({
    postTypeCatalog = {},
    publicPostTypes = {},
    configuredPostTypes,
    onPostTypeTabToggle,
    includeNonPublicPostTypes = false,
    onIncludeNonPublicPostTypesChange,
    globalInvalidation,
    onGlobalInvalidationChange,
    themeContext,
    invalidationBehavior,
    onInvalidationBehaviorChange,
    asyncDelayDefaultSeconds = 10,
    cronDisabled,
    availablePages = [],
    pageSelectionMeta = {},
    timedInvalidation,
    onTimedInvalidationChange,
    siteTimezone = "UTC",
    featureSettings = {},
}) {
    const { async_enabled = false, async_delay_seconds } =
        invalidationBehavior || {};

    const update = (key, value) => {
        if (!onInvalidationBehaviorChange) return;
        onInvalidationBehaviorChange({
            ...(invalidationBehavior || {}),
            [key]: value,
        });
    };

    const updateAsyncDelay = (value) => {
        if (!onInvalidationBehaviorChange) return;

        const next = { ...(invalidationBehavior || {}) };
        const raw =
            typeof value === "string" ? value.trim() : `${value ?? ""}`.trim();

        if (raw === "") {
            // IMPORTANT: allow empty state
            delete next.async_delay_seconds;
            onInvalidationBehaviorChange(next);
            return;
        }

        const parsed = parseInt(raw, 10);
        if (Number.isNaN(parsed)) {
            return; // ignore invalid input (do not overwrite)
        }

        next.async_delay_seconds = parsed;
        onInvalidationBehaviorChange(next);
    };

    const updateGlobalInvalidation = (key, value) => {
        if (!onGlobalInvalidationChange) return;
        onGlobalInvalidationChange({
            ...(globalInvalidation || {}),
            [key]: value,
        });
    };

    const gi = globalInvalidation || {};
    const tc = themeContext || {};
    const themeType = tc.type || "classic";
    const configuredPostTypeLabels = Object.fromEntries(
        (configuredPostTypes || []).map((postType) => [
            postType,
            postTypeCatalog?.[postType]?.label || postType,
        ]),
    );

    const themeLabel =
        themeType === "block" ? __("Block theme", "cache-autopilot") : __("Classic theme", "cache-autopilot");

    return (
        <>
            <CustomSection
                title={__("General", "cache-autopilot")}
                helpUrl={SETTINGS_PANEL_HELP_URLS.general}
            >
                <NextToggleControl
                    label={__("Invalidation engine", "cache-autopilot")}
                    help={__("Enable or disable all cache invalidation.", "cache-autopilot")}
                    checked={gi.plugin_enabled ?? true}
                    onChange={(val) =>
                        updateGlobalInvalidation("plugin_enabled", val)
                    }
                />
            </CustomSection>
            <CustomSection
                title={__("Post Type Tabs", "cache-autopilot")}
                helpUrl={SETTINGS_PANEL_HELP_URLS.groupManagement}
            >
                <SimpleModePanel
                    postTypeCatalog={postTypeCatalog}
                    configuredPostTypes={configuredPostTypes}
                    onTogglePostType={onPostTypeTabToggle}
                    includeNonPublicPostTypes={includeNonPublicPostTypes}
                    onIncludeNonPublicPostTypesChange={
                        onIncludeNonPublicPostTypesChange
                    }
                />
            </CustomSection>
            <TimedInvalidationSlot
                value={timedInvalidation || {}}
                onChange={onTimedInvalidationChange}
                availablePages={availablePages}
                pageSelectionMeta={pageSelectionMeta}
                publicPostTypes={publicPostTypes}
                configuredPostTypes={configuredPostTypeLabels}
                cronDisabled={cronDisabled}
                siteTimezone={siteTimezone}
            />
            <CustomSection
                title={__("Theme & URL Changes", "cache-autopilot")}
                helpUrl={SETTINGS_PANEL_HELP_URLS.themeArchiveChanges}
                collapsible={true}
                initialOpen={false}
            >
                <p className='ekesto-section-description is-small is-italic'>
                    {sprintf(
                        __(
                            "Active theme: %s. All options shown regardless of theme type.",
                            "cache-autopilot",
                        ),
                        themeLabel,
                    )}
                </p>
                {!(gi.plugin_enabled ?? true) && (
                    <Notice status='warning' isDismissible={false}>
                        {__(
                            "Invalidation is paused. No cache purges or URL emissions will run until re-enabled.",
                            "cache-autopilot",
                        )}
                    </Notice>
                )}
                <div className='ekesto-settings-subpanels'>
                    <div className='ekesto-settings-subpanel'>
                        <h3 className='ekesto-settings-subpanel__title'>
                            {__("Theme & UI Surface", "cache-autopilot")}
                        </h3>
                        <div className='settings-inner-container'>
                            <div className='settings-inner-container__item'>
                                <NextToggleControl
                                    label={__("Menu updates", "cache-autopilot")}
                                    help={__(
                                        "Invalidate cache after menu or menu location updates.",
                                        "cache-autopilot",
                                    )}
                                    checked={gi.menus_enabled ?? true}
                                    onChange={(val) =>
                                        updateGlobalInvalidation(
                                            "menus_enabled",
                                            val,
                                        )
                                    }
                                />
                            </div>
                            <div className='settings-inner-container__item'>
                                <NextToggleControl
                                    label={__("Customizer updates", "cache-autopilot")}
                                    help={__(
                                        "Invalidate cache after Customizer saves.",
                                        "cache-autopilot",
                                    )}
                                    checked={gi.customizer_enabled ?? true}
                                    onChange={(val) =>
                                        updateGlobalInvalidation(
                                            "customizer_enabled",
                                            val,
                                        )
                                    }
                                />
                            </div>
                            <div className='settings-inner-container__item'>
                                <NextToggleControl
                                    label={__("Theme switch", "cache-autopilot")}
                                    help={__(
                                        "Invalidate cache after switching the active theme.",
                                        "cache-autopilot",
                                    )}
                                    checked={gi.switch_theme_enabled ?? true}
                                    onChange={(val) =>
                                        updateGlobalInvalidation(
                                            "switch_theme_enabled",
                                            val,
                                        )
                                    }
                                />
                            </div>
                            <div className='settings-inner-container__item'>
                                <NextToggleControl
                                    label={__("Navigation updates", "cache-autopilot")}
                                    help={__(
                                        "Invalidate cache after navigation block updates.",
                                        "cache-autopilot",
                                    )}
                                    checked={gi.navigation_enabled ?? true}
                                    onChange={(val) =>
                                        updateGlobalInvalidation(
                                            "navigation_enabled",
                                            val,
                                        )
                                    }
                                />
                            </div>
                        </div>
                    </div>

                    <div className='ekesto-settings-subpanel'>
                        <h3 className='ekesto-settings-subpanel__title'>
                            {__("Patterns & Widgets", "cache-autopilot")}
                        </h3>
                        <div className='settings-inner-container'>
                            <div className='settings-inner-container__item'>
                                <NextToggleControl
                                    label={__("Widget updates", "cache-autopilot")}
                                    help={__(
                                        "Invalidate cache after widget or sidebar updates.",
                                        "cache-autopilot",
                                    )}
                                    checked={gi.widgets_enabled ?? true}
                                    onChange={(val) =>
                                        updateGlobalInvalidation(
                                            "widgets_enabled",
                                            val,
                                        )
                                    }
                                />
                            </div>
                            <div className='settings-inner-container__item'>
                                <NextToggleControl
                                    label={__("Widget fallback", "cache-autopilot")}
                                    help={__(
                                        "Include configured post type targets when specific widget mapping is unavailable.",
                                        "cache-autopilot",
                                    )}
                                    checked={
                                        gi.widget_global_fallback_enabled ??
                                        true
                                    }
                                    onChange={(val) =>
                                        updateGlobalInvalidation(
                                            "widget_global_fallback_enabled",
                                            val,
                                        )
                                    }
                                />
                            </div>
                            <div className='settings-inner-container__item'>
                                <NextToggleControl
                                    label={__("Synced Pattern updates", "cache-autopilot")}
                                    help={__(
                                        "Invalidate pages referencing an updated synced pattern.",
                                        "cache-autopilot",
                                    )}
                                    checked={gi.synced_patterns_enabled ?? true}
                                    onChange={(val) =>
                                        updateGlobalInvalidation(
                                            "synced_patterns_enabled",
                                            val,
                                        )
                                    }
                                />
                            </div>
                            <div className='settings-inner-container__item'>
                                <NextToggleControl
                                    label={__("Synced Pattern fallback", "cache-autopilot")}
                                    help={__(
                                        "Broaden invalidation when synced pattern references cannot be resolved.",
                                        "cache-autopilot",
                                    )}
                                    checked={
                                        gi.pattern_global_fallback_enabled ??
                                        true
                                    }
                                    onChange={(val) =>
                                        updateGlobalInvalidation(
                                            "pattern_global_fallback_enabled",
                                            val,
                                        )
                                    }
                                />
                            </div>
                        </div>
                    </div>

                    <div className='ekesto-settings-subpanel'>
                        <h3 className='ekesto-settings-subpanel__title'>
                            {__("Content Triggers", "cache-autopilot")}
                        </h3>
                        <div className='settings-inner-container'>
                            <div className='settings-inner-container__item'>
                                <NextToggleControl
                                    label={__("Comment changes", "cache-autopilot")}
                                    help={__(
                                        "Invalidate cache after comment additions, edits, or deletions.",
                                        "cache-autopilot",
                                    )}
                                    checked={gi.comments_enabled ?? true}
                                    onChange={(val) =>
                                        updateGlobalInvalidation(
                                            "comments_enabled",
                                            val,
                                        )
                                    }
                                />
                            </div>
                            <div className='settings-inner-container__item'>
                                <NextToggleControl
                                    label={__("Form changes", "cache-autopilot")}
                                    help={__(
                                        "Invalidate pages embedding an updated form.",
                                        "cache-autopilot",
                                    )}
                                    checked={gi.forms_enabled ?? true}
                                    onChange={(val) =>
                                        updateGlobalInvalidation(
                                            "forms_enabled",
                                            val,
                                        )
                                    }
                                />
                            </div>
                            <div className='settings-inner-container__item'>
                                <NextToggleControl
                                    label={__("Form fallback", "cache-autopilot")}
                                    help={__(
                                        "Broaden invalidation when form references cannot be resolved.",
                                        "cache-autopilot",
                                    )}
                                    checked={
                                        gi.forms_global_fallback_enabled ?? true
                                    }
                                    onChange={(val) =>
                                        updateGlobalInvalidation(
                                            "forms_global_fallback_enabled",
                                            val,
                                        )
                                    }
                                />
                            </div>
                        </div>
                    </div>

                    <MultilingualFanoutSlot
                        globalInvalidation={gi}
                        onChange={updateGlobalInvalidation}
                    />

                    <div className='ekesto-settings-subpanel'>
                        <h3 className='ekesto-settings-subpanel__title'>
                            {__("Site Settings Changes", "cache-autopilot")}
                        </h3>
                        <div className='settings-inner-container'>
                            <div className='settings-inner-container__item'>
                                <NextToggleControl
                                    label={__("Reading settings updates", "cache-autopilot")}
                                    help={__(
                                        "Invalidate cache after front page or posts page updates.",
                                        "cache-autopilot",
                                    )}
                                    checked={
                                        gi.reading_settings_enabled ?? true
                                    }
                                    onChange={(val) =>
                                        updateGlobalInvalidation(
                                            "reading_settings_enabled",
                                            val,
                                        )
                                    }
                                />
                            </div>
                            <div className='settings-inner-container__item'>
                                <NextToggleControl
                                    label={__("Permalink updates", "cache-autopilot")}
                                    help={__(
                                        "Invalidate cache after permalink or URL base updates.",
                                        "cache-autopilot",
                                    )}
                                    checked={
                                        gi.permalink_settings_enabled ?? true
                                    }
                                    onChange={(val) =>
                                        updateGlobalInvalidation(
                                            "permalink_settings_enabled",
                                            val,
                                        )
                                    }
                                />
                            </div>
                        </div>
                    </div>

                    <div className='ekesto-settings-subpanel'>
                        <h3 className='ekesto-settings-subpanel__title'>
                            {__("System Changes", "cache-autopilot")}
                        </h3>
                        <p className='ekesto-section-description is-small is-italic'>
                            {__(
                                "Enable only if your cache plugin does not already handle these events.",
                                "cache-autopilot",
                            )}
                        </p>

                        <div className='settings-inner-container'>
                            <div className='settings-inner-container__item'>
                                <NextToggleControl
                                    label={__("Core updates", "cache-autopilot")}
                                    help={__(
                                        "Triggers a full cache refresh after WordPress core updates.",
                                        "cache-autopilot",
                                    )}
                                    checked={gi.core_update ?? false}
                                    onChange={(val) =>
                                        updateGlobalInvalidation(
                                            "core_update",
                                            val,
                                        )
                                    }
                                />
                            </div>
                            <div className='settings-inner-container__item'>
                                <NextToggleControl
                                    label={__(
                                        "Plugin updates / activation / deactivation",
                                        "cache-autopilot",
                                    )}
                                    help={__(
                                        "Triggers a full cache refresh when plugins change.",
                                        "cache-autopilot",
                                    )}
                                    checked={gi.plugin_update ?? false}
                                    onChange={(val) =>
                                        updateGlobalInvalidation(
                                            "plugin_update",
                                            val,
                                        )
                                    }
                                />
                            </div>
                            <div className='settings-inner-container__item'>
                                <NextToggleControl
                                    label={__("Theme updates", "cache-autopilot")}
                                    help={__(
                                        "Triggers a full cache refresh after theme updates.",
                                        "cache-autopilot",
                                    )}
                                    checked={gi.theme_update ?? false}
                                    onChange={(val) =>
                                        updateGlobalInvalidation(
                                            "theme_update",
                                            val,
                                        )
                                    }
                                />
                            </div>
                        </div>
                    </div>
                </div>
            </CustomSection>
            <CustomSection
                title={__("Invalidation Behavior", "cache-autopilot")}
                helpUrl={SETTINGS_PANEL_HELP_URLS.invalidationBehavior}
                columns={2}
                collapsible={true}
                initialOpen={false}
            >
                <div>
                    <NextToggleControl
                        label={__("Async execution", "cache-autopilot")}
                        help={__(
                            "Run invalidation asynchronously instead of during the current request.",
                            "cache-autopilot",
                        )}
                        checked={async_enabled}
                        onChange={(val) => update("async_enabled", val)}
                    />
                    {cronDisabled && async_enabled && (
                        <Notice status='warning' isDismissible={false}>
                            {__(
                                "DISABLE_WP_CRON is active. Async execution requires a server cron calling wp-cron.php every 1–5 minutes.",
                                "cache-autopilot",
                            )}
                        </Notice>
                    )}
                </div>
                <NextNumberControl
                    label={__("Delay (seconds)", "cache-autopilot")}
                    help={sprintf(
                        __(
                            "Seconds to wait before processing the queue. Batches rapid changes. Default: %d",
                            "cache-autopilot",
                        ),
                        asyncDelayDefaultSeconds,
                    )}
                    value={async_delay_seconds ?? undefined}
                    placeholder={asyncDelayDefaultSeconds}
                    onChange={updateAsyncDelay}
                    min={1}
                    max={300}
                />
            </CustomSection>
            <AccessControlSlot
                featureSettings={featureSettings}
            />
            <CustomSection
                title={__("Support & Debugging", "cache-autopilot")}
                helpUrl={SETTINGS_PANEL_HELP_URLS.supportDebugging}
                collapsible={true}
                initialOpen={false}
            >
                <SupportDebugPanel />
            </CustomSection>
        </>
    );
}
