import { useState } from "@wordpress/element";
import { __ } from "@wordpress/i18n";
import { useDispatch } from "@wordpress/data";
import { store as noticesStore } from "@wordpress/notices";
import { Button, Icon } from "@wordpress/components";
import { check, cancelCircleFilled as errorIcon } from "@wordpress/icons";
import apiFetch from "@wordpress/api-fetch";
import { getFallbackReasonDisplay } from "../utils/fallbackReason";

function ResultRow({ label, value, text = "" }) {
    return (
        <tr>
            <th style={{ width: "260px" }}>{label}</th>
            <td>
                <code>{value}</code>
                {text ? <p className='description'>{text}</p> : null}
            </td>
        </tr>
    );
}

export default function WarmupCapability({ options, setOptions }) {
    const probeResults = options?.diagnostics?.probe_results || null;
    const [running, setRunning] = useState(false);
    const [selfCheck, setSelfCheck] = useState(null);
    const [selfCheckRunning, setSelfCheckRunning] = useState(false);
    const { createSuccessNotice, createErrorNotice } = useDispatch(noticesStore);

    const handleProbe = async () => {
        setRunning(true);
        try {
            const data = await apiFetch({
                path: "/ekesto-cache-warmup/v1/warmup-probe",
                method: "POST",
            });
            setOptions({
                ...options,
                diagnostics: {
                    ...(options.diagnostics || {}),
                    probe_results: data,
                },
            });
            createSuccessNotice(
                probeResults
                    ? __("Transport status refreshed.", "cache-autopilot")
                    : __("Transport status checked.", "cache-autopilot"),
                {
                    type: "snackbar",
                    icon: <Icon icon={check} />,
                },
            );
        } catch (err) {
            createErrorNotice(
                err?.message || __("Failed to refresh transport status.", "cache-autopilot"),
                {
                    type: "snackbar",
                    icon: <Icon icon={errorIcon} />,
                },
            );
        } finally {
            setRunning(false);
        }
    };

    const handleSelfCheck = async () => {
        setSelfCheckRunning(true);
        try {
            const data = await apiFetch({
                path: "/ekesto-cache-warmup/v1/http-self-check",
                method: "POST",
            });
            setSelfCheck(data.wp_http_self_check);
            createSuccessNotice(
                __("Self-check completed.", "cache-autopilot"),
                {
                    type: "snackbar",
                    icon: <Icon icon={check} />,
                },
            );
        } catch (err) {
            createErrorNotice(
                err?.message || __("Self-check failed.", "cache-autopilot"),
                {
                    type: "snackbar",
                    icon: <Icon icon={errorIcon} />,
                },
            );
        } finally {
            setSelfCheckRunning(false);
        }
    };

    const strategy = probeResults?.strategy || "";
    const strategyLabel = (() => {
        if (strategy === "brotli_profile_with_fallback") {
            return __("Browser-profile request with standard fallback", "cache-autopilot");
        }
        if (strategy === "standard_request_only") {
            return __("Standard WordPress HTTP request only", "cache-autopilot");
        }
        return "\u2014";
    })();

    const checkedAt = probeResults?.tested_at
        ? new Date(probeResults.tested_at).toLocaleString()
        : "\u2014";

    const p90Effective = Number.isFinite(probeResults?.p90_effective_ms)
        ? String(probeResults.p90_effective_ms)
        : "\u2014";
    const p90Brotli = Number.isFinite(probeResults?.p90_brotli_ms)
        ? String(probeResults.p90_brotli_ms)
        : "\u2014";
    const p90Fallback = Number.isFinite(probeResults?.p90_fallback_ms)
        ? String(probeResults.p90_fallback_ms)
        : "\u2014";

    const fallbackRate = probeResults?.sample_count > 0
        && Number.isFinite(probeResults?.fallback_rate_pct)
        ? `${probeResults.fallback_rate_pct}%`
        : "\u2014";
    const lastFallbackAt = probeResults?.last_fallback_at_ts
        ? new Date(probeResults.last_fallback_at_ts * 1000).toLocaleString()
        : null;
    const lastFallbackReason = getFallbackReasonDisplay(
        probeResults?.last_fallback_reason,
    ).text;
    const unavailableReason = getFallbackReasonDisplay(
        probeResults?.brotli_profile_unavailable_reason,
    ).text;
    const showPerformanceNote = probeResults && (
        fallbackRate === "\u2014"
        || p90Effective === "\u2014"
        || p90Brotli === "\u2014"
        || p90Fallback === "\u2014"
    );

    const selfCheckCheckedAt = selfCheck?.checked_at
        ? new Date(selfCheck.checked_at).toLocaleString()
        : null;

    return (
        <>
            <p className='ekesto-section-description'>
                {__(
                    "Shows the active request strategy and performance across up to 200 recent warmup requests.",
                    "cache-autopilot",
                )}
            </p>

            <div className='ecw-manual-run'>
                <Button
                    variant='secondary'
                    onClick={handleProbe}
                    disabled={running}
                    isBusy={running}
                    className='ecw-manual-run__button'
                >
                    {probeResults
                        ? __("Refresh transport status", "cache-autopilot")
                        : __("Check transport status", "cache-autopilot")}
                </Button>
            </div>

            {probeResults && (
                <div className='ekesto-responsive-table-container'>
                    <div className='ekesto-responsive-table-inner'>
                        <table
                            className='widefat striped ecw-diagnostics-table'
                            style={{ maxWidth: "600px" }}
                        >
                            <tbody>
                                <ResultRow
                                    label={__("Strategy", "cache-autopilot")}
                                    value={strategyLabel}
                                />
                                <ResultRow
                                    label={__("Browser-profile request", "cache-autopilot")}
                                    value={probeResults.brotli_profile_available
                                        ? __("Available", "cache-autopilot")
                                        : __("Unavailable", "cache-autopilot")}
                                />
                                {!probeResults.brotli_profile_available && (
                                    <ResultRow
                                        label={__("Unavailable reason", "cache-autopilot")}
                                        value={unavailableReason || "\u2014"}
                                    />
                                )}
                                <ResultRow
                                    label={__("Recent warmup requests", "cache-autopilot")}
                                    value={String(probeResults.sample_count || 0)}
                                />
                                <ResultRow
                                    label={__("Standard fallback rate", "cache-autopilot")}
                                    value={fallbackRate}
                                />
                                <ResultRow
                                    label={__("p90 total request (ms)", "cache-autopilot")}
                                    value={p90Effective}
                                />
                                <ResultRow
                                    label={__("p90 browser-profile request (ms)", "cache-autopilot")}
                                    value={p90Brotli}
                                />
                                <ResultRow
                                    label={__("p90 standard fallback (ms)", "cache-autopilot")}
                                    value={p90Fallback}
                                />
                                {lastFallbackAt && (
                                    <ResultRow
                                        label={__("Last standard fallback", "cache-autopilot")}
                                        value={lastFallbackAt}
                                        text={lastFallbackReason}
                                    />
                                )}
                                <ResultRow
                                    label={__("Checked at", "cache-autopilot")}
                                    value={checkedAt}
                                />
                            </tbody>
                        </table>
                    </div>
                </div>
            )}
            {showPerformanceNote && (
                <p className='ekesto-section-description'>
                    {__(
                        "Performance values appear as data is collected. p90 requires at least 10 requests; fallback p90 requires at least 10 fallbacks.",
                        "cache-autopilot",
                    )}
                </p>
            )}
            <h4 className='ecw-subsection-title'>
                {__("Connectivity", "cache-autopilot")}
            </h4>
            <p className='ekesto-section-description'>
                {__(
                    "Tests whether WordPress can reach this site via its HTTP API.",
                    "cache-autopilot",
                )}
            </p>

            <div className='ecw-manual-run'>
                <Button
                    variant='secondary'
                    onClick={handleSelfCheck}
                    disabled={selfCheckRunning}
                    isBusy={selfCheckRunning}
                    className='ecw-manual-run__button'
                >
                    {__("Run self-check", "cache-autopilot")}
                </Button>
            </div>

            {selfCheck ? (
                <div className='ekesto-responsive-table-container'>
                    <div className='ekesto-responsive-table-inner'>
                        <table
                            className='widefat striped ecw-diagnostics-table'
                            style={{ maxWidth: "600px" }}
                        >
                            <tbody>
                                <ResultRow
                                    label={__("Result", "cache-autopilot")}
                                    value={selfCheck.success ? "OK" : "FAIL"}
                                />
                                <ResultRow
                                    label={__("HTTP status", "cache-autopilot")}
                                    value={Number.isFinite(selfCheck.http_code) ? String(selfCheck.http_code) : "\u2014"}
                                />
                                <ResultRow
                                    label={__("Message", "cache-autopilot")}
                                    value={selfCheck.message || "\u2014"}
                                />
                                <ResultRow
                                    label={__("Response time (ms)", "cache-autopilot")}
                                    value={String(selfCheck.elapsed_ms)}
                                />
                                <ResultRow
                                    label={__("Target URL", "cache-autopilot")}
                                    value={selfCheck.target_url}
                                />
                                <ResultRow
                                    label={__("Checked at", "cache-autopilot")}
                                    value={selfCheckCheckedAt || "\u2014"}
                                />
                            </tbody>
                        </table>
                    </div>
                </div>
            ) : (
                <p className='ekesto-section-description'>
                    <em>{__("Not checked yet.", "cache-autopilot")}</em>
                </p>
            )}
        </>
    );
}
