import { useCallback, useEffect, useMemo, useState } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import axios from '../../../bootstrap';
import { PANEL_ROUTES, settingsSubTabFromPath, type SettingsSubTabId } from '../../../navigation/panelRoutes';
import { timeAgo } from '../../../utils/timeAgo';
import { useTimeTicker } from '../../../utils/useTimeTicker';
import {
    Settings,
    Clock,
    Copy,
    CheckCircle2,
    RefreshCw,
    Loader2,
    AlertTriangle,
    Terminal,
    Send,
    Wrench,
    Bell,
} from 'lucide-react';
import { CollapsibleSection } from '../../../components/CollapsibleSection';
import { ListPagination } from '../../../components/ListPagination';

interface CronSettings {
    secret_key: string;
    rotated_at: string | null;
    base_url: string;
    endpoints: {
        schedule: string;
        queue: string;
        all: string;
    };
    last_runs?: {
        schedule_cron: string | null;
        queue_cron: string | null;
        scheduler_tasks: string | null;
    };
    queue_last_processed?: {
        name?: string;
        queue?: string;
        processed_at?: string;
    } | null;
}

interface TelegramNotificationType {
    key: string;
    label: string;
    description: string;
    category: string;
    severity: string;
    enabled: boolean;
}

interface TelegramNotificationSettings {
    categories: Record<string, string>;
    types: TelegramNotificationType[];
}

interface MaintenanceSettings {
    stale_command_hours: number;
    auto_retry_commands: string[];
    stale_commands: number;
    active_commands: number;
    failed_queue_jobs: number;
}

interface CronJobInstruction {
    id: string;
    title: string;
    schedule: string;
    description: string;
    endpointKey: keyof CronSettings['endpoints'];
    recommended: boolean;
}

const NOTIFICATION_CATEGORIES_PER_PAGE = 2;

const SETTINGS_TABS: Array<{ id: SettingsSubTabId; label: string; icon: typeof Clock }> = [
    { id: 'cron', label: 'Cron Jobs', icon: Clock },
    { id: 'telegram', label: 'Telegram Notifications', icon: Send },
    { id: 'maintenance', label: 'Maintenance', icon: Wrench },
];

const CRON_JOBS: CronJobInstruction[] = [
    {
        id: 'schedule',
        title: 'Laravel Scheduler',
        schedule: '* * * * *',
        description: 'Runs scheduled tasks such as offline detection and incident auto-resolve.',
        endpointKey: 'schedule',
        recommended: true,
    },
    {
        id: 'queue',
        title: 'Queue Worker',
        schedule: '* * * * *',
        description: 'Processes pending jobs (Telegram alerts, sync tasks, etc.) until the queue is empty.',
        endpointKey: 'queue',
        recommended: true,
    },
    {
        id: 'all',
        title: 'Combined (Alternative)',
        schedule: '* * * * *',
        description: 'Runs both scheduler and queue in one request. Use this only if your host limits cron entries.',
        endpointKey: 'all',
        recommended: false,
    },
];

function buildCronCommand(url: string): string {
    return `curl -s ${url} >/dev/null 2>&1`;
}

function buildFullCronLine(schedule: string, url: string): string {
    return `${schedule} ${buildCronCommand(url)}`;
}

function severityClass(severity: string): string {
    switch (severity) {
        case 'critical':
            return 'bg-rose-500/10 text-rose-400 border-rose-500/20';
        case 'warning':
            return 'bg-amber-500/10 text-amber-400 border-amber-500/20';
        default:
            return 'bg-slate-500/10 text-slate-400 border-slate-600/30';
    }
}

function ToggleSwitch({
    checked,
    disabled,
    onChange,
}: {
    checked: boolean;
    disabled?: boolean;
    onChange: (checked: boolean) => void;
}) {
    return (
        <button
            type="button"
            role="switch"
            aria-checked={checked}
            disabled={disabled}
            onClick={() => onChange(!checked)}
            className={`relative inline-flex h-6 w-11 shrink-0 items-center rounded-full border transition-colors disabled:opacity-50 ${
                checked
                    ? 'bg-emerald-500/80 border-emerald-400/40'
                    : 'bg-slate-800 border-slate-700'
            }`}
        >
            <span
                className={`inline-block h-4 w-4 transform rounded-full bg-white shadow transition-transform ${
                    checked ? 'translate-x-6' : 'translate-x-1'
                }`}
            />
        </button>
    );
}

function cronFreshnessClass(value: string | null | undefined, nowTick: number): string {
    if (!value) {
        return 'text-slate-500';
    }

    const seconds = Math.max(0, Math.floor((nowTick - new Date(value).getTime()) / 1000));

    if (seconds <= 120) {
        return 'text-emerald-400';
    }

    if (seconds <= 300) {
        return 'text-amber-400';
    }

    return 'text-rose-400';
}

function cronFreshnessLabel(value: string | null | undefined, nowTick: number): string {
    if (!value) {
        return 'Never';
    }

    const seconds = Math.max(0, Math.floor((nowTick - new Date(value).getTime()) / 1000));

    if (seconds <= 120) {
        return 'Healthy';
    }

    if (seconds <= 300) {
        return 'Delayed';
    }

    return 'Stale';
}

export function SettingsView() {
    const location = useLocation();
    const navigate = useNavigate();
    const activeTab = settingsSubTabFromPath(location.pathname);

    const [cron, setCron] = useState<CronSettings | null>(null);
    const [telegramNotifications, setTelegramNotifications] = useState<TelegramNotificationSettings | null>(null);
    const [maintenance, setMaintenance] = useState<MaintenanceSettings | null>(null);
    const [isLoading, setIsLoading] = useState(true);
    const [error, setError] = useState<string | null>(null);
    const [success, setSuccess] = useState<string | null>(null);
    const [isRegenerating, setIsRegenerating] = useState(false);
    const [savingNotificationKey, setSavingNotificationKey] = useState<string | null>(null);
    const [runningMaintenanceAction, setRunningMaintenanceAction] = useState<string | null>(null);
    const [copiedId, setCopiedId] = useState<string | null>(null);
    const [notificationCategoryPage, setNotificationCategoryPage] = useState(1);
    const nowTick = useTimeTicker(15000);

    const fetchSettings = useCallback(async (silent = false) => {
        if (!silent) {
            setIsLoading(true);
        }
        setError(null);

        try {
            const response = await axios.get('/settings');
            setCron(response.data.cron);
            setTelegramNotifications(response.data.telegram_notifications);
            setMaintenance(response.data.maintenance ?? null);
        } catch (err: any) {
            if (!silent) {
                const status = err.response?.status;
                if (status === 404) {
                    setError(
                        'Settings API not found on the server. Upload the latest routes/admin.php and app/Features/System files, then run: php artisan route:clear && php artisan config:clear && composer dump-autoload -o',
                    );
                } else if (status === 401) {
                    setError('Your session expired. Sign in again and reload this page.');
                } else {
                    setError(err.response?.data?.message || 'Could not load panel settings.');
                }
            }
        } finally {
            if (!silent) {
                setIsLoading(false);
            }
        }
    }, []);

    useEffect(() => {
        fetchSettings();
    }, [fetchSettings]);

    useEffect(() => {
        if (activeTab !== 'cron' && activeTab !== 'maintenance') {
            return;
        }

        const timer = window.setInterval(() => {
            fetchSettings(true);
        }, 15000);

        return () => window.clearInterval(timer);
    }, [activeTab, fetchSettings]);

    const handleCopy = async (id: string, text: string) => {
        try {
            await navigator.clipboard.writeText(text);
            setCopiedId(id);
            window.setTimeout(() => setCopiedId(null), 2000);
        } catch {
            setError('Could not copy to clipboard.');
        }
    };

    const handleRegenerate = async () => {
        if (
            !window.confirm(
                'Regenerate the cron secret key? Existing cron URLs will stop working until you update them on your server.',
            )
        ) {
            return;
        }

        setIsRegenerating(true);
        setError(null);
        setSuccess(null);

        try {
            const response = await axios.post('/settings/cron-secret/regenerate');
            setCron(response.data.cron);
            setSuccess(response.data.message || 'Cron secret key regenerated.');
        } catch (err: any) {
            setError(err.response?.data?.message || 'Failed to regenerate cron secret key.');
        } finally {
            setIsRegenerating(false);
        }
    };

    const handleMaintenanceAction = async (
        actionId: string,
        endpoint: string,
        confirmMessage?: string,
        payload?: Record<string, unknown>,
    ) => {
        if (confirmMessage && !window.confirm(confirmMessage)) {
            return;
        }

        setRunningMaintenanceAction(actionId);
        setError(null);
        setSuccess(null);

        try {
            const response = await axios.post(endpoint, payload ?? {});
            if (response.data.maintenance) {
                setMaintenance(response.data.maintenance);
            }
            setSuccess(response.data.message || 'Maintenance action completed.');
            await fetchSettings(true);
        } catch (err: any) {
            setError(err.response?.data?.message || 'Maintenance action failed.');
        } finally {
            setRunningMaintenanceAction(null);
        }
    };

    const handleNotificationToggle = async (key: string, enabled: boolean) => {
        if (!telegramNotifications) {
            return;
        }

        const previous = telegramNotifications;
        setTelegramNotifications({
            ...telegramNotifications,
            types: telegramNotifications.types.map((item) =>
                item.key === key ? { ...item, enabled } : item,
            ),
        });
        setSavingNotificationKey(key);
        setError(null);
        setSuccess(null);

        try {
            const response = await axios.put('/settings/telegram-notifications', {
                notifications: { [key]: enabled },
            });
            setTelegramNotifications(response.data.telegram_notifications);
            setSuccess('Telegram notification preference saved.');
        } catch (err: any) {
            setTelegramNotifications(previous);
            setError(err.response?.data?.message || 'Failed to save notification preference.');
        } finally {
            setSavingNotificationKey(null);
        }
    };

    const groupedNotificationTypes = telegramNotifications
        ? Object.entries(telegramNotifications.categories).map(([categoryKey, categoryLabel]) => ({
              categoryKey,
              categoryLabel,
              items: telegramNotifications.types.filter((item) => item.category === categoryKey),
          }))
        : [];

    const enabledNotificationCount = telegramNotifications?.types.filter((item) => item.enabled).length ?? 0;
    const totalNotificationCount = telegramNotifications?.types.length ?? 0;

    const notificationCategoryTotalPages = Math.max(
        1,
        Math.ceil(groupedNotificationTypes.length / NOTIFICATION_CATEGORIES_PER_PAGE),
    );
    const paginatedNotificationCategories = useMemo(() => {
        const start = (notificationCategoryPage - 1) * NOTIFICATION_CATEGORIES_PER_PAGE;
        return groupedNotificationTypes.slice(start, start + NOTIFICATION_CATEGORIES_PER_PAGE);
    }, [groupedNotificationTypes, notificationCategoryPage]);

    useEffect(() => {
        if (notificationCategoryPage > notificationCategoryTotalPages) {
            setNotificationCategoryPage(notificationCategoryTotalPages);
        }
    }, [notificationCategoryPage, notificationCategoryTotalPages]);

    const settingsPathForTab = (tab: SettingsSubTabId): string => {
        switch (tab) {
            case 'telegram':
                return PANEL_ROUTES.settingsTelegram;
            case 'maintenance':
                return PANEL_ROUTES.settingsMaintenance;
            default:
                return PANEL_ROUTES.settingsCron;
        }
    };

    if (isLoading) {
        return (
            <div className="flex items-center justify-center min-h-[40vh]">
                <Loader2 className="w-8 h-8 text-rose-500 animate-spin" />
            </div>
        );
    }

    return (
        <div className="space-y-6 max-w-4xl">
            <div>
                <h1 className="text-2xl font-bold text-slate-100 flex items-center gap-2">
                    <Settings className="w-6 h-6 text-rose-400" />
                    Settings
                </h1>
                <p className="text-sm text-slate-500 mt-1">
                    Panel configuration, cron setup, and notification preferences.
                </p>
            </div>

            {error && (
                <div className="flex items-start gap-2 rounded-xl border border-rose-500/20 bg-rose-500/10 px-4 py-3 text-sm text-rose-300">
                    <AlertTriangle className="w-4 h-4 shrink-0 mt-0.5" />
                    {error}
                </div>
            )}

            {success && (
                <div className="flex items-start gap-2 rounded-xl border border-emerald-500/20 bg-emerald-500/10 px-4 py-3 text-sm text-emerald-300">
                    <CheckCircle2 className="w-4 h-4 shrink-0 mt-0.5" />
                    {success}
                </div>
            )}

            <div className="flex flex-wrap gap-2 border-b border-slate-800 pb-3">
                {SETTINGS_TABS.map((tab) => {
                    const Icon = tab.icon;
                    const isActive = activeTab === tab.id;

                    return (
                        <button
                            key={tab.id}
                            type="button"
                            onClick={() => navigate(settingsPathForTab(tab.id))}
                            className={`inline-flex items-center gap-2 px-4 py-2 text-sm font-semibold rounded-xl transition-all ${
                                isActive
                                    ? 'bg-rose-500 text-white shadow-md'
                                    : 'text-slate-400 hover:text-slate-200 border border-transparent hover:bg-slate-900/50'
                            }`}
                        >
                            <Icon className="w-4 h-4" />
                            {tab.label}
                            {tab.id === 'telegram' && totalNotificationCount > 0 && (
                                <span
                                    className={`text-[10px] px-1.5 py-0.5 rounded-full ${
                                        isActive ? 'bg-white/20 text-white' : 'bg-slate-800 text-slate-400'
                                    }`}
                                >
                                    {enabledNotificationCount}/{totalNotificationCount}
                                </span>
                            )}
                            {tab.id === 'maintenance' && maintenance && maintenance.stale_commands > 0 && (
                                <span
                                    className={`text-[10px] px-1.5 py-0.5 rounded-full ${
                                        isActive ? 'bg-white/20 text-white' : 'bg-amber-500/20 text-amber-300'
                                    }`}
                                >
                                    {maintenance.stale_commands}
                                </span>
                            )}
                        </button>
                    );
                })}
            </div>

            {activeTab === 'cron' && (
                <section className="rounded-2xl border border-slate-800/80 bg-slate-900/40 overflow-hidden">
                    <div className="px-5 py-4 border-b border-slate-800/60 flex flex-wrap items-center justify-between gap-3">
                        <div>
                            <h2 className="text-base font-semibold text-slate-100 flex items-center gap-2">
                                <Clock className="w-4 h-4 text-sky-400" />
                                Cron Jobs (cPanel / Shared Hosting)
                            </h2>
                            <p className="text-xs text-slate-500 mt-1">
                                Add these HTTP cron jobs on your server. No SSH or artisan access required.
                            </p>
                        </div>
                        <button
                            type="button"
                            onClick={handleRegenerate}
                            disabled={isRegenerating}
                            className="inline-flex items-center gap-2 px-3 py-2 rounded-xl text-xs font-semibold uppercase tracking-wide border border-amber-500/30 bg-amber-500/10 text-amber-300 hover:bg-amber-500/20 disabled:opacity-50"
                        >
                            {isRegenerating ? (
                                <Loader2 className="w-3.5 h-3.5 animate-spin" />
                            ) : (
                                <RefreshCw className="w-3.5 h-3.5" />
                            )}
                            Regenerate Secret Key
                        </button>
                    </div>

                    <div className="px-5 py-4 space-y-4 border-b border-slate-800/60 bg-slate-950/30">
                        <div className="grid gap-3 sm:grid-cols-2">
                            <div>
                                <p className="text-[10px] uppercase tracking-widest text-slate-500 font-semibold mb-1">
                                    Panel URL
                                </p>
                                <p className="text-sm text-slate-300 font-mono break-all">{cron?.base_url || '—'}</p>
                            </div>
                            <div>
                                <p className="text-[10px] uppercase tracking-widest text-slate-500 font-semibold mb-1">
                                    Secret Key Last Rotated
                                </p>
                                <p className="text-sm text-slate-300">
                                    {cron?.rotated_at ? new Date(cron.rotated_at).toLocaleString() : 'Not rotated yet'}
                                </p>
                            </div>
                        </div>

                        <div className="rounded-xl border border-sky-500/20 bg-sky-500/5 px-4 py-3 text-xs text-sky-200/90 leading-relaxed">
                            <strong className="text-sky-300">Recommended:</strong> Add cron jobs #1 and #2 (every minute).
                            Use #3 only if your host allows a single cron entry. After regenerating the secret key, update
                            all cron commands on your server.
                        </div>
                    </div>

                    <div className="px-5 py-4 border-b border-slate-800/60 bg-slate-950/20">
                        <p className="text-[10px] uppercase tracking-widest text-slate-500 font-semibold mb-3">
                            Cron Activity
                        </p>
                        <div className="grid gap-3 sm:grid-cols-2">
                            {[
                                {
                                    label: 'Scheduler Cron (#1)',
                                    value: cron?.last_runs?.schedule_cron ?? null,
                                    hint: 'Last HTTP hit on /cron/.../schedule',
                                },
                                {
                                    label: 'Queue Cron (#2)',
                                    value: cron?.last_runs?.queue_cron ?? null,
                                    hint: 'Last HTTP hit on /cron/.../queue',
                                },
                                {
                                    label: 'Scheduled Tasks',
                                    value: cron?.last_runs?.scheduler_tasks ?? null,
                                    hint: 'Last time offline detection and other scheduled tasks ran',
                                },
                                {
                                    label: 'Last Queue Job',
                                    value: cron?.queue_last_processed?.processed_at ?? null,
                                    hint: cron?.queue_last_processed?.name
                                        ? `${cron.queue_last_processed.name} processed`
                                        : 'Last job processed by the queue worker',
                                },
                            ].map((item) => (
                                <div
                                    key={item.label}
                                    className="rounded-xl border border-slate-800/70 bg-slate-950/40 px-4 py-3"
                                >
                                    <div className="flex items-start justify-between gap-2">
                                        <p className="text-xs font-semibold text-slate-200">{item.label}</p>
                                        <span
                                            className={`text-[10px] uppercase tracking-widest font-semibold ${cronFreshnessClass(item.value, nowTick)}`}
                                        >
                                            {cronFreshnessLabel(item.value, nowTick)}
                                        </span>
                                    </div>
                                    <p className={`text-sm font-medium mt-1 ${cronFreshnessClass(item.value, nowTick)}`}>
                                        {item.value ? timeAgo(item.value, nowTick) : 'Never'}
                                    </p>
                                    <p className="text-[11px] text-slate-600 mt-1">{item.hint}</p>
                                    {item.value && (
                                        <p className="text-[10px] text-slate-600 font-mono mt-1">
                                            {new Date(item.value).toLocaleString()}
                                        </p>
                                    )}
                                </div>
                            ))}
                        </div>
                    </div>

                    <div className="divide-y divide-slate-800/60">
                        {cron &&
                            CRON_JOBS.map((job, index) => {
                                const url = cron.endpoints[job.endpointKey];
                                const fullLine = buildFullCronLine(job.schedule, url);
                                const copyKey = `cron-${job.id}`;

                                return (
                                    <div key={job.id} className="px-5 py-4 space-y-3">
                                        <div className="flex flex-wrap items-start justify-between gap-2">
                                            <div>
                                                <h3 className="text-sm font-semibold text-slate-100 flex items-center gap-2">
                                                    <Terminal className="w-3.5 h-3.5 text-slate-500" />
                                                    {index + 1}. {job.title}
                                                    {job.recommended ? (
                                                        <span className="text-[10px] uppercase tracking-widest px-2 py-0.5 rounded-full border border-emerald-500/30 bg-emerald-500/10 text-emerald-400">
                                                            Required
                                                        </span>
                                                    ) : (
                                                        <span className="text-[10px] uppercase tracking-widest px-2 py-0.5 rounded-full border border-slate-600/50 bg-slate-800/50 text-slate-400">
                                                            Optional
                                                        </span>
                                                    )}
                                                </h3>
                                                <p className="text-xs text-slate-500 mt-1">{job.description}</p>
                                            </div>
                                            <code className="text-[11px] text-slate-400 font-mono bg-slate-950/60 px-2 py-1 rounded-lg border border-slate-800/80">
                                                {job.schedule}
                                            </code>
                                        </div>

                                        <div className="relative">
                                            <pre className="text-xs font-mono text-slate-300 bg-slate-950/70 border border-slate-800/80 rounded-xl p-3 overflow-x-auto whitespace-pre-wrap break-all">
                                                {fullLine}
                                            </pre>
                                            <button
                                                type="button"
                                                onClick={() => handleCopy(copyKey, fullLine)}
                                                className="absolute top-2 right-2 inline-flex items-center gap-1 px-2 py-1 rounded-lg text-[10px] font-semibold uppercase tracking-wide border border-slate-700/80 bg-slate-900/90 text-slate-300 hover:text-white"
                                            >
                                                {copiedId === copyKey ? (
                                                    <>
                                                        <CheckCircle2 className="w-3 h-3 text-emerald-400" />
                                                        Copied
                                                    </>
                                                ) : (
                                                    <>
                                                        <Copy className="w-3 h-3" />
                                                        Copy
                                                    </>
                                                )}
                                            </button>
                                        </div>

                                        <p className="text-[11px] text-slate-600 font-mono break-all">URL: {url}</p>
                                    </div>
                                );
                            })}
                    </div>
                </section>
            )}

            {activeTab === 'telegram' && (
                <section className="space-y-3">
                    <div className="rounded-2xl border border-slate-800/80 bg-slate-900/40 px-5 py-4">
                        <div className="flex flex-wrap items-start justify-between gap-3">
                            <div>
                                <h2 className="text-base font-semibold text-slate-100 flex items-center gap-2">
                                    <Send className="w-4 h-4 text-sky-400" />
                                    Telegram Notifications
                                </h2>
                                <p className="text-xs text-slate-500 mt-1">
                                    Tap a category to expand. Disabled notifications are skipped before delivery.
                                </p>
                            </div>
                            <div className="rounded-xl border border-slate-800/80 bg-slate-900/60 px-3 py-2 text-xs text-slate-400">
                                <span className="text-slate-200 font-semibold">{enabledNotificationCount}</span> of{' '}
                                <span className="text-slate-200 font-semibold">{totalNotificationCount}</span> enabled
                            </div>
                        </div>
                    </div>

                    {paginatedNotificationCategories.map(({ categoryKey, categoryLabel, items }) => {
                        const enabledInCategory = items.filter((item) => item.enabled).length;

                        return (
                            <CollapsibleSection
                                key={categoryKey}
                                id={`telegram-notifications-${categoryKey}`}
                                title={categoryLabel}
                                icon={Bell}
                                defaultOpen={false}
                                badge={
                                    <span className="rounded-full border border-slate-700/80 bg-slate-800/80 px-2 py-0.5 text-[9px] font-semibold text-slate-400">
                                        {enabledInCategory}/{items.length} on
                                    </span>
                                }
                            >
                                <div className="space-y-3 p-4">
                                    {items.map((item) => (
                                        <div
                                            key={item.key}
                                            className="flex items-start justify-between gap-4 rounded-xl border border-slate-800/70 bg-slate-950/30 px-4 py-3"
                                        >
                                            <div className="min-w-0">
                                                <div className="flex flex-wrap items-center gap-2">
                                                    <p className="text-sm font-medium text-slate-100">{item.label}</p>
                                                    <span
                                                        className={`text-[10px] uppercase tracking-widest px-2 py-0.5 rounded-full border ${severityClass(item.severity)}`}
                                                    >
                                                        {item.severity}
                                                    </span>
                                                </div>
                                                <p className="text-xs text-slate-500 mt-1">{item.description}</p>
                                            </div>
                                            <div className="flex items-center gap-2 shrink-0 pt-0.5">
                                                {savingNotificationKey === item.key && (
                                                    <Loader2 className="w-3.5 h-3.5 text-slate-500 animate-spin" />
                                                )}
                                                <ToggleSwitch
                                                    checked={item.enabled}
                                                    disabled={savingNotificationKey === item.key}
                                                    onChange={(enabled) => handleNotificationToggle(item.key, enabled)}
                                                />
                                            </div>
                                        </div>
                                    ))}
                                </div>
                            </CollapsibleSection>
                        );
                    })}

                    {groupedNotificationTypes.length > 0 ? (
                        <div className="rounded-2xl border border-slate-800/80 bg-slate-900/40">
                            <ListPagination
                                page={notificationCategoryPage}
                                totalPages={notificationCategoryTotalPages}
                                totalItems={groupedNotificationTypes.length}
                                pageSize={NOTIFICATION_CATEGORIES_PER_PAGE}
                                onPageChange={setNotificationCategoryPage}
                            />
                        </div>
                    ) : null}
                </section>
            )}

            {activeTab === 'maintenance' && (
                <section className="rounded-2xl border border-slate-800/80 bg-slate-900/40 overflow-hidden">
                    <div className="px-5 py-4 border-b border-slate-800/60 bg-slate-950/30">
                        <h2 className="text-base font-semibold text-slate-100 flex items-center gap-2">
                            <Wrench className="w-4 h-4 text-sky-400" />
                            System Maintenance
                        </h2>
                        <p className="text-xs text-slate-500 mt-1">
                            Clear stuck tasks, flush failed queue jobs, and reset panel cache. Stale agent commands older
                            than {maintenance?.stale_command_hours ?? 2} hours are auto-cancelled and re-queued every 15
                            minutes.
                        </p>
                    </div>

                    <div className="px-5 py-4 grid gap-3 sm:grid-cols-3 border-b border-slate-800/60">
                        <div className="rounded-xl border border-slate-800/70 bg-slate-950/40 px-4 py-3">
                            <p className="text-[10px] uppercase tracking-widest text-slate-500 font-semibold">Stale Commands</p>
                            <p className="text-2xl font-bold text-amber-400 mt-1">{maintenance?.stale_commands ?? 0}</p>
                        </div>
                        <div className="rounded-xl border border-slate-800/70 bg-slate-950/40 px-4 py-3">
                            <p className="text-[10px] uppercase tracking-widest text-slate-500 font-semibold">Active Commands</p>
                            <p className="text-2xl font-bold text-slate-100 mt-1">{maintenance?.active_commands ?? 0}</p>
                        </div>
                        <div className="rounded-xl border border-slate-800/70 bg-slate-950/40 px-4 py-3">
                            <p className="text-[10px] uppercase tracking-widest text-slate-500 font-semibold">Failed Queue Jobs</p>
                            <p className="text-2xl font-bold text-rose-400 mt-1">{maintenance?.failed_queue_jobs ?? 0}</p>
                        </div>
                    </div>

                    <div className="divide-y divide-slate-800/60">
                        {[
                            {
                                id: 'recover-stale',
                                title: 'Recover Stale Commands',
                                description:
                                    'Cancel commands running longer than 2 hours and automatically queue a fresh retry for scans, sync, and similar tasks.',
                                endpoint: '/settings/maintenance/recover-stale-commands',
                                button: 'Run Recovery Now',
                                style: 'border-sky-500/30 bg-sky-500/10 text-sky-300 hover:bg-sky-500/20',
                            },
                            {
                                id: 'clear-pending',
                                title: 'Clear All Pending Commands',
                                description:
                                    'Force-cancel every pending or running agent command immediately without creating retries.',
                                endpoint: '/settings/maintenance/clear-pending-commands',
                                button: 'Clear Pending',
                                style: 'border-amber-500/30 bg-amber-500/10 text-amber-300 hover:bg-amber-500/20',
                                confirm:
                                    'Clear all pending and running agent commands? This cannot be undone.',
                            },
                            {
                                id: 'clear-cache',
                                title: 'Clear Application Cache',
                                description: 'Run cache, config, route, and view clear commands on the panel server.',
                                endpoint: '/settings/maintenance/clear-cache',
                                button: 'Clear Cache',
                                style: 'border-slate-700 bg-slate-900/60 text-slate-200 hover:bg-slate-800/60',
                            },
                            {
                                id: 'flush-failed',
                                title: 'Flush Failed Queue Jobs',
                                description: 'Delete all failed queue jobs (Telegram alerts, notifications, etc.).',
                                endpoint: '/settings/maintenance/flush-failed-jobs',
                                button: 'Flush Failed Jobs',
                                style: 'border-rose-500/30 bg-rose-500/10 text-rose-300 hover:bg-rose-500/20',
                                confirm: 'Delete all failed queue jobs?',
                            },
                        ].map((action) => (
                            <div key={action.id} className="px-5 py-4 flex flex-wrap items-start justify-between gap-4">
                                <div className="max-w-2xl">
                                    <h3 className="text-sm font-semibold text-slate-100">{action.title}</h3>
                                    <p className="text-xs text-slate-500 mt-1">{action.description}</p>
                                </div>
                                <button
                                    type="button"
                                    disabled={runningMaintenanceAction !== null}
                                    onClick={() =>
                                        handleMaintenanceAction(
                                            action.id,
                                            action.endpoint,
                                            action.confirm,
                                        )
                                    }
                                    className={`inline-flex items-center gap-2 px-4 py-2 rounded-xl text-xs font-semibold uppercase tracking-wide border disabled:opacity-50 ${action.style}`}
                                >
                                    {runningMaintenanceAction === action.id ? (
                                        <Loader2 className="w-3.5 h-3.5 animate-spin" />
                                    ) : null}
                                    {action.button}
                                </button>
                            </div>
                        ))}
                    </div>
                </section>
            )}
        </div>
    );
}
