import { __ } from "@wordpress/i18n";
import { useState } from "@wordpress/element";
import { NextNumberControl, NextTextControl } from "../components/NextControls";
import CustomSection from "../components/CustomSection";
import { RadioControl, Button } from "@wordpress/components";
import apiFetch from "@wordpress/api-fetch";

const CACHE_WARMUP_DOCS_URL = "https://wpcacheautopilot.com/docs/cache-warmup/";
const ADVANCED_PANEL_HELP_URLS = {
    warmupEngine: `${CACHE_WARMUP_DOCS_URL}#warmup-engine`,
    userAgent: `${CACHE_WARMUP_DOCS_URL}#user-agent`,
    queueBehavior: `${CACHE_WARMUP_DOCS_URL}#queue-behavior`,
};

const toIntOrNull = (value) =>
    value === "" || value === undefined || value === null
        ? null
        : parseInt(value, 10);

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

export default function AdvancedTab({ options, setOptions, onResetTuningSuccess, onResetTuningError }) {
    const [resettingTuning, setResettingTuning] = useState(false);
    const [tuningStatsState, setTuningStatsState] = useState(
        () => window.EkestoCacheWarmup?.tuningStats ?? {},
    );
    const [safeCapsState, setSafeCapsState] = useState(
        () => window.EkestoCacheWarmup?.safeCaps ?? {},
    );
    const [batchPreviewState, setBatchPreviewState] = useState(
        () => window.EkestoCacheWarmup?.batchPreview ?? {},
    );

    const buildResetTuningStats = (currentStats) => ({
        ...currentStats,
        sample_count_window: 0,
        sample_count_total: 0,
        p90_ms: null,
        is_sufficient: false,
        last_computed: null,
    });

    const buildResetSafeCaps = (currentCaps) => ({
        ...currentCaps,
        recommended_pages_per_batch: null,
        recommended_max_batch_seconds: null,
    });

    const buildResetBatchPreview = (currentPreview) => {
        const mode = (options.advanced?.pacing_mode ?? "auto") === "manual"
            ? "manual"
            : "auto";
        const configuredFallback = toFiniteIntOrNull(options.advanced?.pages_per_batch)
            ?? toFiniteIntOrNull(currentPreview?.configured_pages_per_batch)
            ?? toFiniteIntOrNull(advancedDefaults.pages_per_batch)
            ?? 1;
        const dynamicSystemCap = toFiniteIntOrNull(currentPreview?.dynamic_system_cap)
            ?? toFiniteIntOrNull(safeCaps.pages_per_batch)
            ?? 1;

        if (mode === "auto") {
            return {
                ...currentPreview,
                configured_pages_per_batch: configuredFallback,
                effective_pages_per_batch: Math.max(1, Math.min(10, dynamicSystemCap)),
                dynamic_system_cap: dynamicSystemCap,
                basis: "bootstrap",
            };
        }

        return {
            ...currentPreview,
            configured_pages_per_batch: configuredFallback,
            effective_pages_per_batch: Math.max(1, Math.min(configuredFallback, dynamicSystemCap)),
            dynamic_system_cap: dynamicSystemCap,
            basis: "manual_no_telemetry",
        };
    };

    const handleResetTuningData = async () => {
        if (!window.confirm(__("Reset all collected tuning data? This will clear timing samples used for automatic pacing.", "cache-autopilot"))) {
            return;
        }
        setResettingTuning(true);
        try {
            await apiFetch({
                path: "/ekesto-cache-warmup/v1/tuning-stats/reset",
                method: "POST",
            });

            const nextTuningStats = buildResetTuningStats(tuningStatsState);
            const nextSafeCaps = buildResetSafeCaps(safeCapsState);
            const nextBatchPreview = buildResetBatchPreview(batchPreviewState);

            setTuningStatsState(nextTuningStats);
            setSafeCapsState(nextSafeCaps);
            setBatchPreviewState(nextBatchPreview);

            if (window.EkestoCacheWarmup) {
                window.EkestoCacheWarmup.tuningStats = nextTuningStats;
                window.EkestoCacheWarmup.safeCaps = nextSafeCaps;
                window.EkestoCacheWarmup.batchPreview = nextBatchPreview;
            }

            onResetTuningSuccess?.();
        } catch (err) {
            console.error(err);
            onResetTuningError?.();
        } finally {
            setResettingTuning(false);
        }
    };

    const advanced = options.advanced || {};

    const runtimeDefaults = window.EkestoCacheWarmup?.runtimeDefaults ?? {};
    const advancedDefaults = runtimeDefaults.advanced ?? {};
    const tuningStats = tuningStatsState;
    const safeCaps = safeCapsState;
    const batchPreview = batchPreviewState;

    const pacingMode = advanced.pacing_mode ?? 'auto';
    const isAutoMode = pacingMode !== 'manual';
    const lastComputed = tuningStats.last_computed ?? null;
    const hasComputed =
        lastComputed &&
        typeof lastComputed === "object" &&
        Number.isFinite(lastComputed.pages_per_batch) &&
        Number.isFinite(lastComputed.max_batch_seconds);
    const hasTelemetryRecommendation =
        tuningStats.is_sufficient &&
        hasComputed &&
        (lastComputed.basis ?? "") === "telemetry";
    const p90Label =
        tuningStats.p90_ms != null && tuningStats.p90_ms > 0
            ? `${tuningStats.p90_ms}ms`
            : "—";
    const sampleWindow = Number.isFinite(tuningStats.sample_count_window)
        ? tuningStats.sample_count_window
        : 0;
    const previewConfiguredPages = Number.isFinite(batchPreview.configured_pages_per_batch)
        ? batchPreview.configured_pages_per_batch
        : null;
    const previewEffectivePages = Number.isFinite(batchPreview.effective_pages_per_batch)
        ? batchPreview.effective_pages_per_batch
        : null;
    const previewBasis = typeof batchPreview.basis === "string"
        ? batchPreview.basis
        : "";
    const hasBatchPreview = previewConfiguredPages !== null && previewEffectivePages !== null;
    const isTelemetryPreview = previewBasis === "telemetry";

    const phpLimits = window.EkestoCacheWarmup?.phpLimits ?? {};

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

    return (
        <>
            <CustomSection
                title={__("Warmup Engine", "cache-autopilot")}
                helpUrl={ADVANCED_PANEL_HELP_URLS.warmupEngine}
                description={__(
                    "Each WP-Cron run processes a batch of URLs, limited by count and time.",
                    "cache-autopilot",
                )}
            >
                <RadioControl
                    label={__("Tuning Mode", "cache-autopilot")}
                    selected={pacingMode}
                    className='ecw-tuning-mode-control'
                    options={[
                        {
                            label: __("Automatic (Recommended)", "cache-autopilot"),
                            value: "auto",
                        },
                        { label: __("Manual", "cache-autopilot"), value: "manual" },
                    ]}
                    onChange={(value) => updateAdvanced("pacing_mode", value)}
                />

                {isAutoMode && (
                    <>
                        <p className='ekesto-section-description'>
                            {__(
                                "Automatically adjusts limits based on server capacity and past warmup performance.",
                                "cache-autopilot",
                            )}
                        </p>
                        <div className='ecw-auto-pacing-info'>
                            {hasComputed ? (
                                <>
                                    <p>
                                        {__("Current auto limits: up to ", "cache-autopilot")}
                                        <strong>
                                            {lastComputed.pages_per_batch}
                                        </strong>{" "}
                                        {__("URLs or ", "cache-autopilot")}
                                        <strong>
                                            {lastComputed.max_batch_seconds}s
                                        </strong>{" "}
                                        {__("per cron run.", "cache-autopilot")}
                                    </p>
                                    {hasTelemetryRecommendation ? (
                                        <p>
                                            {__(
                                                "Computed from recent warmup latency: p90 ",
                                                "cache-autopilot",
                                            )}
                                            <strong>{p90Label}</strong>
                                            {__(" across ", "cache-autopilot")}
                                            <strong>{sampleWindow}</strong>
                                            {__(" recent requests.", "cache-autopilot")}
                                        </p>
                                    ) : (
                                        <p>
                                            {__(
                                                "Collecting recent telemetry: ",
                                                "cache-autopilot",
                                            )}
                                            <strong>{sampleWindow}/30</strong>
                                            {__(
                                                " samples collected. Conservative startup limits are used until enough data is available.",
                                                "cache-autopilot",
                                            )}
                                        </p>
                                    )}
                                </>
                            ) : (
                                <p>
                                    {__(
                                        "No runtime telemetry yet. Auto mode will start with conservative limits after the first warmup run.",
                                        "cache-autopilot",
                                    )}
                                </p>
                            )}
                        </div>
                    </>
                )}

                {!isAutoMode && (
                    <>
                        <p className='ekesto-section-description'>
                            {__("Set fixed limits yourself.", "cache-autopilot")}
                        </p>
                        <div className='ecw-auto-pacing-info'>
                            {hasTelemetryRecommendation ? (
                                <p>
                                    {__(
                                        "Your server typically responds in ",
                                        "cache-autopilot",
                                    )}
                                    <strong>{p90Label}</strong>
                                    {__(" (p90) across ", "cache-autopilot")}
                                    <strong>{sampleWindow}</strong>
                                    {__(" recent warmup requests.", "cache-autopilot")}
                                </p>
                            ) : (
                                <p>
                                    {__(
                                        "Not enough recent telemetry yet to provide performance insights.",
                                        "cache-autopilot",
                                    )}
                                    {" ("}
                                    {sampleWindow}
                                    {"/30 samples collected)"}
                                </p>
                            )}
                        </div>
                        <div className='settings-inner-container col-3'>
                            <div className='settings-inner-container__item'>
                                <NextNumberControl
                                    label={__("Max URLs per cron run", "cache-autopilot")}
                                    help={__(
                                        "Actual count depends on response times and batch duration.",
                                        "cache-autopilot",
                                    )}
                                    value={advanced.pages_per_batch ?? ""}
                                    placeholder={String(
                                        advancedDefaults.pages_per_batch ?? "",
                                    )}
                                    onChange={(value) =>
                                        updateAdvanced(
                                            "pages_per_batch",
                                            toIntOrNull(value),
                                        )
                                    }
                                    min={1}
                                    max={safeCaps.pages_per_batch ?? 1000}
                                />
                                {hasBatchPreview && (
                                    <p className='ecw-field-hint'>
                                        {__("Configured: ", "cache-autopilot")}
                                        <strong>{previewConfiguredPages}</strong>
                                        {" · "}
                                        {__("Effective: ", "cache-autopilot")}
                                        <strong>
                                            {isTelemetryPreview
                                                ? `~${previewEffectivePages}`
                                                : previewEffectivePages}
                                        </strong>
                                        {" ("}
                                        {isTelemetryPreview
                                            ? __("based on current performance", "cache-autopilot")
                                            : __("based on current configuration", "cache-autopilot")}
                                        {")"}
                                    </p>
                                )}
                                {hasTelemetryRecommendation &&
                                    safeCaps.recommended_pages_per_batch !=
                                        null && (
                                        <p className='ecw-field-hint'>
                                            {__("Recommended ceiling: ", "cache-autopilot")}
                                            {
                                                safeCaps.recommended_pages_per_batch
                                            }
                                        </p>
                                    )}
                                {hasTelemetryRecommendation &&
                                    safeCaps.recommended_pages_per_batch !=
                                        null &&
                                    (advanced.pages_per_batch ?? 0) >
                                        safeCaps.recommended_pages_per_batch && (
                                        <p className='ecw-field-warning'>
                                            {__(
                                                "Exceeds safe recommendation of ",
                                                "cache-autopilot",
                                            )}
                                            {
                                                safeCaps.recommended_pages_per_batch
                                            }
                                            {__(" — may risk timeout", "cache-autopilot")}
                                        </p>
                                    )}
                            </div>

                            <div className='settings-inner-container__item'>
                                <NextNumberControl
                                    label={__("Max batch duration (s)", "cache-autopilot")}
                                    help={__(
                                        "Maximum seconds a batch may run.",
                                        "cache-autopilot",
                                    )}
                                    value={advanced.max_batch_seconds ?? ""}
                                    placeholder={String(
                                        advancedDefaults.max_batch_seconds ??
                                            "",
                                    )}
                                    onChange={(value) =>
                                        updateAdvanced(
                                            "max_batch_seconds",
                                            toIntOrNull(value),
                                        )
                                    }
                                    min={5}
                                    max={safeCaps.max_batch_seconds ?? 120}
                                />
                                <p className='ecw-field-hint'>
                                    {__("Server PHP execution limit: ", "cache-autopilot")}
                                    <strong>
                                        {phpLimits.max_execution_time}s
                                    </strong>
                                </p>
                                {hasTelemetryRecommendation &&
                                    safeCaps.recommended_max_batch_seconds !=
                                        null && (
                                        <p className='ecw-field-hint'>
                                            {__("Recommended: ", "cache-autopilot")}
                                            {
                                                safeCaps.recommended_max_batch_seconds
                                            }
                                            s{" ("}
                                            {__(
                                                "based on PHP execution limit",
                                                "cache-autopilot",
                                            )}
                                            {")"}
                                        </p>
                                    )}
                                {hasTelemetryRecommendation &&
                                    safeCaps.recommended_max_batch_seconds !=
                                        null &&
                                    (advanced.max_batch_seconds ?? 0) >
                                        safeCaps.recommended_max_batch_seconds && (
                                        <p className='ecw-field-warning'>
                                            {__(
                                                "Exceeds safe recommendation of ",
                                                "cache-autopilot",
                                            )}
                                            {
                                                safeCaps.recommended_max_batch_seconds
                                            }
                                            s{__(" — may risk timeout", "cache-autopilot")}
                                        </p>
                                    )}
                            </div>

                            <div className='settings-inner-container__item'>
                                <NextNumberControl
                                    label={__("Delay between requests (s)", "cache-autopilot")}
                                    help={__(
                                        "Seconds between each request. 0 for no delay.",
                                        "cache-autopilot",
                                    )}
                                    value={advanced.throttle_seconds ?? ""}
                                    placeholder={String(
                                        advancedDefaults.throttle_seconds ?? "",
                                    )}
                                    onChange={(value) =>
                                        updateAdvanced(
                                            "throttle_seconds",
                                            toIntOrNull(value),
                                        )
                                    }
                                    min={0}
                                    max={5}
                                />
                            </div>
                        </div>
                    </>
                )}
                <p className='ekesto-section-description is-small is-italic'>
                    <strong>{__("p90 ", "cache-autopilot")}</strong>
                    {__(
                        "is the response time 90% of requests complete within.",
                        "cache-autopilot",
                    )}
                </p>
                <div className='ecw-tuning-reset'>
                    <Button
                        variant='secondary'
                        onClick={handleResetTuningData}
                        disabled={resettingTuning}
                        isBusy={resettingTuning}
                        className='ecw-manual-run__button'
                    >
                        {__("Reset Tuning Data", "cache-autopilot")}
                    </Button>
                    <p className='ecw-manual-run__description mt-md'>
                        {__(
                            "Clears timing samples used for automatic pacing.",
                            "cache-autopilot",
                        )}
                    </p>
                </div>
            </CustomSection>
            <CustomSection
                title={__("User Agent", "cache-autopilot")}
                helpUrl={ADVANCED_PANEL_HELP_URLS.userAgent}
                description={__(
                    "Used to exclude warmup requests in analytics tools.",
                    "cache-autopilot",
                )}
                columns={2}
            >
                <NextTextControl
                    label={__("User-Agent", "cache-autopilot")}
                    help={
                        __(
                            "Appended to warmup request headers. Leave empty for default: ",
                            "cache-autopilot",
                        ) + String(advancedDefaults.user_agent ?? "")
                    }
                    value={advanced.user_agent ?? ""}
                    placeholder={String(advancedDefaults.user_agent ?? "")}
                    onChange={(value) => updateAdvanced("user_agent", value)}
                />
            </CustomSection>
            <CustomSection
                title={__("Queue Behavior", "cache-autopilot")}
                helpUrl={ADVANCED_PANEL_HELP_URLS.queueBehavior}
                description={__(
                    "Defaults are used when a field is left blank. Override only what your host or workflow requires.",
                    "cache-autopilot",
                )}
                columns={2}
            >
                <NextNumberControl
                    label={__("Stale run threshold (minutes)", "cache-autopilot")}
                    help={__(
                        "A run with no progress for this long is marked stale.",
                        "cache-autopilot",
                    )}
                    value={advanced.stale_run_minutes ?? ""}
                    placeholder={String(
                        advancedDefaults.stale_run_minutes ?? "",
                    )}
                    onChange={(value) =>
                        updateAdvanced("stale_run_minutes", toIntOrNull(value))
                    }
                    min={5}
                    max={1440}
                />

                <NextNumberControl
                    label={__("Max queued URLs per run", "cache-autopilot")}
                    help={__(
                        "Maximum URLs per warmup run.",
                        "cache-autopilot",
                    )}
                    value={advanced.max_urls_per_run ?? ""}
                    placeholder={String(
                        advancedDefaults.max_urls_per_run ?? "",
                    )}
                    onChange={(value) =>
                        updateAdvanced("max_urls_per_run", toIntOrNull(value))
                    }
                    min={100}
                    max={100000}
                />
            </CustomSection>
        </>
    );
}
