import { __, sprintf } from "@wordpress/i18n";
import { Button } from "@wordpress/components";
import { NextToggleControl, NextTextareaControl } from "../components/NextControls";
import CustomSection from "../components/CustomSection";

const CACHE_WARMUP_DOCS_URL = "https://wpcacheautopilot.com/docs/cache-warmup/";
const WARMUP_PANEL_HELP_URLS = {
    general: `${CACHE_WARMUP_DOCS_URL}#general`,
    sitemaps: `${CACHE_WARMUP_DOCS_URL}#sitemaps`,
};

export default function WarmupTab({
    options,
    setOptions,
    savedSitemapUrls = [],
    onRunFullWarmup,
    runFullBusy = false,
    runFullDisabled = false,
    runFullHelperText = "",
}) {
    const general = options.general || {};

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

    const getSitemapLabel = (url) => {
        try {
            const parsed = new URL(url);
            const segments = parsed.pathname.split("/").filter(Boolean);
            return segments.length > 0 ? segments[segments.length - 1] : parsed.hostname;
        } catch {
            return url;
        }
    };

    return (
        <>
            <CustomSection
                title={__("General", "cache-autopilot")}
                helpUrl={WARMUP_PANEL_HELP_URLS.general}
                columns={2}
            >
                <NextToggleControl
                    label={__("Automatic warmup", "cache-autopilot")}
                    help={__(
                        "Rebuilds cache after changes and purges in background batches.",
                        "cache-autopilot",
                    )}
                    checked={general.enabled || false}
                    onChange={(value) => updateGeneralField("enabled", value)}
                />
                <div className='ecw-manual-run'>
                    <Button
                        variant='secondary'
                        onClick={onRunFullWarmup}
                        disabled={runFullDisabled || runFullBusy}
                        isBusy={runFullBusy}
                        className='ecw-manual-run__button'
                    >
                        {__("Trigger full cache refresh", "cache-autopilot")}
                    </Button>
                    <p className='ecw-manual-run__description'>
                        {runFullHelperText ||
                            __(
                                "The cache is invalidated first, then all sitemap URLs are warmed in background batches via WP-Cron.",
                                "cache-autopilot",
                            )}
                    </p>
                </div>
            </CustomSection>

            <CustomSection
                title={__("Sitemaps", "cache-autopilot")}
                helpUrl={WARMUP_PANEL_HELP_URLS.sitemaps}
                columns={2}
            >
                <div>
                    <NextTextareaControl
                        label={__("Sitemap URL(s)", "cache-autopilot")}
                        help={__(
                            "One URL per line. Sitemap indexes are supported.",
                            "cache-autopilot",
                        )}
                        value={general.sitemaps || ""}
                        onChange={(value) =>
                            updateGeneralField("sitemaps", value)
                        }
                        rows={6}
                    />
                    {savedSitemapUrls.length > 0 && (
                        <div className='ecw-sitemap-preview mt-md'>
                            {savedSitemapUrls.length === 1 ? (
                                <a
                                    href={savedSitemapUrls[0]}
                                    target='_blank'
                                    rel='noopener noreferrer'
                                    className='ecw-sitemap-preview__link'
                                >
                                    {__("Preview sitemap ↗", "cache-autopilot")}
                                </a>
                            ) : (
                                savedSitemapUrls.map((url, index) => (
                                    <p
                                        key={`${url}-${index}`}
                                        className='ecw-sitemap-preview__item'
                                    >
                                        <a
                                            href={url}
                                            target='_blank'
                                            rel='noopener noreferrer'
                                            className='ecw-sitemap-preview__link'
                                        >
                                            {sprintf(
                                                __("Preview %s  ↗", "cache-autopilot"),
                                                getSitemapLabel(url),
                                            )}
                                        </a>
                                    </p>
                                ))
                            )}
                        </div>
                    )}
                </div>
                <NextTextareaControl
                    rows={6}
                    value={general.manual_urls || ""}
                    onChange={(value) =>
                        updateGeneralField("manual_urls", value)
                    }
                    label={__("Manual URL Exclusions", "cache-autopilot")}
                    help={__(
                        "One URL per line. These URLs are skipped during warmup.",
                        "cache-autopilot",
                    )}
                />
            </CustomSection>
        </>
    );
}
