/**
 * Admin > System > Storage
 */
const { html } = window;
const { useState, useEffect, useCallback } = hooks;

export default function StorageSection() {
    const [status, setStatus] = useState(null);
    const [orphans, setOrphans] = useState(null);
    const [extraction, setExtraction] = useState(null);
    const [loading, setLoading] = useState(true);

    const load = useCallback(async () => {
        try {
            const [s, o, e] = await Promise.all([
                sw.api.admin.storage.status(),
                sw.api.admin.storage.orphans(),
                sw.api.admin.storage.extraction().catch(() => null),
            ]);
            setStatus(s);
            setOrphans(o);
            setExtraction(e);
        } catch (e) { sw.toast(e.message, 'error'); }
        finally { setLoading(false); }
    }, []);

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

    async function cleanup() {
        const ok = await sw.confirm('Remove orphaned blobs?');
        if (!ok) return;
        try {
            await sw.api.admin.storage.cleanup();
            sw.toast('Cleanup complete', 'success');
            load();
        } catch (e) { sw.toast(e.message, 'error'); }
    }

    function formatBytes(b) {
        if (!b) return '0 B';
        if (b < 1024) return b + ' B';
        if (b < 1048576) return (b / 1024).toFixed(1) + ' KB';
        if (b < 1073741824) return (b / 1048576).toFixed(1) + ' MB';
        return (b / 1073741824).toFixed(2) + ' GB';
    }

    if (loading) return html`<div class="settings-placeholder">Loading\u2026</div>`;

    return html`
        <div>
            ${status && html`
                <div class="stat-cards-grid" style="margin-bottom:16px;">
                    <div class="stat-card"><div class="stat-value">${status.backend || '\u2014'}</div><div class="stat-label">Backend</div></div>
                    <div class="stat-card"><div class="stat-value"><span class="badge ${status.healthy ? 'badge-active' : 'badge-inactive'}">${status.healthy ? 'Healthy' : 'Unhealthy'}</span></div><div class="stat-label">Status</div></div>
                    <div class="stat-card"><div class="stat-value">${status.file_count ?? '\u2014'}</div><div class="stat-label">Files</div></div>
                    <div class="stat-card"><div class="stat-value">${formatBytes(status.total_bytes)}</div><div class="stat-label">Total Size</div></div>
                </div>
            `}

            ${orphans && html`
                <div class="settings-section" style="margin-bottom:16px;">
                    <h4>Orphaned Blobs</h4>
                    <p class="text-muted" style="font-size:12px;">${orphans.count || 0} orphans found</p>
                    ${(orphans.count || 0) > 0 && html`<button class="btn-small btn-primary" onClick=${cleanup}>Clean Up</button>`}
                </div>
            `}

            ${extraction && html`
                <div class="settings-section">
                    <h4>Extraction Queue</h4>
                    <pre class="code-block" style="font-size:12px;max-height:200px;overflow:auto;">${JSON.stringify(extraction, null, 2)}</pre>
                </div>
            `}
        </div>
    `;
}
