import { __ } from "@wordpress/i18n";
import { useState } from "@wordpress/element";
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 { NextNumberControl } from "../components/NextControls";
import CustomSection from "../components/CustomSection";
import RecentLogs from "../components/RecentLogs";

const CACHE_WARMUP_DOCS_URL = "https://wpcacheautopilot.com/docs/cache-warmup/";
const LOGGING_PANEL_HELP_URLS = {
    logSettings: `${CACHE_WARMUP_DOCS_URL}#log-settings`,
    recentRuns: `${CACHE_WARMUP_DOCS_URL}#recent-runs`,
};

export default function LoggingTab({
    options,
    setOptions,
    onRunSuccess,
    recentLogs,
    recentLogsMeta,
    recentLogsLoading,
    recentLogsError,
    logsTimezone,
    onRefreshRecentLogs,
    onLoadAllRecentLogs,
    canLoadAllRecentLogs,
    queueRuntime = { queue_active: false, run_now_actionable: false },
    queueRuntimeLoaded = false,
}) {
    const logging = options.logging || {};
    const [runningNow, setRunningNow] = useState(false);
    const { createSuccessNotice, createErrorNotice } = useDispatch(noticesStore);

    const runtimeDefaults = window.EkestoCacheWarmup?.runtimeDefaults ?? {};
    const loggingDefaults = runtimeDefaults.logging ?? {};

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

    const handleRunNow = async () => {
        setRunningNow(true);
        try {
            const response = await apiFetch({
                path: "/ekesto-cache-warmup/v1/run-now",
                method: "POST",
            });
            if (onRunSuccess) {
                await onRunSuccess(response);
            }
        } catch (err) {
            console.error(err);
            createErrorNotice(
                err?.data?.message ||
                    err?.message ||
                    __("Failed to run the next warmup batch.", "cache-autopilot"),
                {
                    type: "snackbar",
                    icon: <Icon icon={errorIcon} />,
                },
            );
        } finally {
            setRunningNow(false);
        }
    };

    const handleRefreshRecentLogs = async () => {
        if (typeof onRefreshRecentLogs !== "function") {
            return;
        }

        try {
            await onRefreshRecentLogs();
            createSuccessNotice(__("Logs reloaded.", "cache-autopilot"), {
                type: "snackbar",
                icon: <Icon icon={check} />,
            });
        } catch (err) {
            createErrorNotice(err?.message || __("Failed to reload logs.", "cache-autopilot"), {
                type: "snackbar",
                icon: <Icon icon={errorIcon} />,
            });
            throw err;
        }
    };

    return (
        <>
            <CustomSection
                title={__("Recent runs", "cache-autopilot")}
                helpUrl={LOGGING_PANEL_HELP_URLS.recentRuns}
            >
                <div className='ecw-manual-run'>
                    <Button
                        variant='secondary'
                        onClick={handleRunNow}
                        disabled={
                            runningNow ||
                            !queueRuntimeLoaded ||
                            !queueRuntime.run_now_actionable
                        }
                        isBusy={runningNow}
                        className='ecw-manual-run__button'
                    >
                        {__("Run Next Warmup Batch", "cache-autopilot")}
                    </Button>
                    <p className='ecw-manual-run__description mb-lg'>
                        {__(
                            "Executes the next queued warmup batch immediately. Useful if WP-Cron is delayed or disabled.",
                            "cache-autopilot",
                        )}
                    </p>
                </div>

                <RecentLogs
                    logs={recentLogs}
                    logsMeta={recentLogsMeta}
                    loading={recentLogsLoading}
                    error={recentLogsError}
                    tz={logsTimezone}
                    onRefresh={handleRefreshRecentLogs}
                    onLoadRemaining={onLoadAllRecentLogs}
                    canLoadRemaining={canLoadAllRecentLogs}
                />
            </CustomSection>

            <CustomSection
                title={__("Log Settings", "cache-autopilot")}
                helpUrl={LOGGING_PANEL_HELP_URLS.logSettings}
                columns={2}
            >
                <NextNumberControl
                    label={__("Log retention", "cache-autopilot")}
                    help={__("Days to keep run logs. Default: 30.", "cache-autopilot")}
                    value={logging.retention_days ?? ""}
                    placeholder={String(loggingDefaults.retention_days ?? "")}
                    onChange={(value) =>
                        updateField("retention_days", parseInt(value, 10))
                    }
                    min={1}
                    max={365}
                />
            </CustomSection>
        </>
    );
}
