import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
import { useCallback, useState, useEffect, useMemo } from "react";
import { Button } from "../../../components/ui/button";
import { useEditContext } from "../../client/editContext";
import { getSystemStatus } from "../../services/systemService";
import { CheckCircle, AlertCircle, AlertTriangle, Info, RefreshCw, ArrowRight, } from "lucide-react";
/**
 * Settings panel that displays system status and configuration issues.
 * Runs all registered status checks and displays actionable items.
 */
export function StatusPanel() {
    const editContext = useEditContext();
    const [checkStatuses, setCheckStatuses] = useState([]);
    const [overallState, setOverallState] = useState("idle");
    const statusChecks = editContext?.configuration?.statusChecks || [];
    // Initialize check statuses when checks change
    useEffect(() => {
        if (statusChecks.length > 0) {
            setCheckStatuses(statusChecks.map((check) => ({
                id: check.id,
                name: check.name,
                state: "idle",
                results: [],
                isBlocking: check.isBlocking ?? false,
            })));
        }
    }, [statusChecks]);
    const runAllChecks = useCallback(async (options) => {
        if (statusChecks.length === 0) {
            setOverallState("success");
            return;
        }
        setOverallState("loading");
        // Initialize all checks as loading
        setCheckStatuses(statusChecks.map((check) => ({
            id: check.id,
            name: check.name,
            state: "loading",
            results: [],
            isBlocking: check.isBlocking ?? false,
        })));
        if (options?.refreshSystemStatusFirst) {
            await getSystemStatus({ force: true });
        }
        // Run all checks in parallel
        const checkPromises = statusChecks.map(async (check) => {
            try {
                const results = await check.check();
                return {
                    id: check.id,
                    name: check.name,
                    state: "success",
                    results,
                    isBlocking: check.isBlocking ?? false,
                };
            }
            catch (e) {
                return {
                    id: check.id,
                    name: check.name,
                    state: "error",
                    results: [
                        {
                            id: `${check.id}-error`,
                            title: `${check.name} Check Failed`,
                            description: e?.message || "An error occurred during the check",
                            severity: "error",
                        },
                    ],
                    isBlocking: check.isBlocking ?? false,
                };
            }
        });
        const results = await Promise.all(checkPromises);
        setCheckStatuses(results);
        setOverallState("success");
    }, [statusChecks]);
    // Run checks on mount
    useEffect(() => {
        runAllChecks();
    }, [runAllChecks]);
    // Aggregate all issues from all checks
    const allIssues = useMemo(() => {
        return checkStatuses.flatMap((status) => status.results);
    }, [checkStatuses]);
    // Group issues by severity
    const issuesBySeverity = useMemo(() => {
        const errors = allIssues.filter((issue) => issue.severity === "error");
        const warnings = allIssues.filter((issue) => issue.severity === "warning");
        const infos = allIssues.filter((issue) => issue.severity === "info");
        return { errors, warnings, infos };
    }, [allIssues]);
    // Check if there are any blocking issues (from blocking checks that have issues)
    const hasBlockingIssues = useMemo(() => {
        return checkStatuses.some((status) => status.isBlocking && status.results.length > 0);
    }, [checkStatuses]);
    const handleNavigate = useCallback((issue) => {
        if (!issue.targetPanel)
            return;
        // Navigate to the target settings panel via switchWorkspace so the
        // SettingsView picks up the new ccpanel param (plain updateUrl uses
        // pushState which doesn't trigger re-renders in SettingsView).
        editContext?.switchWorkspace("settings", {
            skipConfirmation: true,
            urlParams: { ccpanel: issue.targetPanel },
        });
        // If there's a hash, set it after a small delay
        if (issue.targetHash && typeof window !== "undefined") {
            setTimeout(() => {
                window.location.hash = issue.targetHash;
            }, 50);
        }
    }, [editContext]);
    const getSeverityIcon = (severity) => {
        switch (severity) {
            case "error":
                return (_jsx(AlertCircle, { className: "h-5 w-5 text-red-500", strokeWidth: 1.5 }));
            case "warning":
                return (_jsx(AlertTriangle, { className: "h-5 w-5 text-amber-500", strokeWidth: 1.5 }));
            case "info":
                return _jsx(Info, { className: "h-5 w-5 text-blue-500", strokeWidth: 1.5 });
        }
    };
    const getSeverityBorder = (severity) => {
        switch (severity) {
            case "error":
                return "border-red-200 bg-red-50";
            case "warning":
                return "border-amber-200 bg-amber-50";
            case "info":
                return "border-blue-200 bg-blue-50";
        }
    };
    const isLoading = overallState === "loading";
    const hasIssues = allIssues.length > 0;
    return (_jsx("div", { className: "h-full overflow-auto p-4", children: _jsxs("div", { className: "mx-auto max-w-3xl", children: [_jsxs("div", { className: "mb-6 flex items-center justify-between", children: [_jsx("div", { className: "flex items-center gap-3", children: isLoading ? (_jsxs(_Fragment, { children: [_jsx(RefreshCw, { className: "h-5 w-5 animate-spin text-amber-600", strokeWidth: 1.5 }), _jsx("span", { className: "text-sm text-gray-600", children: "Running status checks..." })] })) : hasIssues ? (_jsxs(_Fragment, { children: [_jsx(AlertTriangle, { className: "h-5 w-5 text-amber-500", strokeWidth: 1.5 }), _jsxs("span", { className: "text-sm text-gray-600", children: [allIssues.length, " issue", allIssues.length !== 1 ? "s" : "", " ", "found", issuesBySeverity.errors.length > 0 && (_jsxs("span", { className: "ml-1 text-red-600", children: ["(", issuesBySeverity.errors.length, " error", issuesBySeverity.errors.length !== 1 ? "s" : "", ")"] }))] })] })) : null }), _jsx("div", { className: "flex items-center gap-2", children: _jsxs(Button, { size: "sm", variant: "outline", onClick: () => void runAllChecks({ refreshSystemStatusFirst: true }), disabled: isLoading, children: [_jsx(RefreshCw, { className: `mr-1 h-4 w-4 ${isLoading ? "animate-spin" : ""}`, strokeWidth: 1.5 }), "Refresh"] }) })] }), isLoading && (_jsxs("div", { className: "mb-6 space-y-2 rounded-lg border border-gray-200 bg-gray-50 p-4", children: [_jsx("div", { className: "text-sm font-medium text-gray-700", children: "Running checks:" }), _jsx("div", { className: "space-y-1", children: checkStatuses.map((status) => (_jsxs("div", { className: "flex items-center gap-2 text-sm", children: [status.state === "loading" ? (_jsx(RefreshCw, { className: "h-3 w-3 animate-spin text-amber-500" })) : status.state === "success" ? (_jsx(CheckCircle, { className: "h-3 w-3 text-green-500" })) : (_jsx(AlertCircle, { className: "h-3 w-3 text-red-500" })), _jsx("span", { className: "text-gray-600", children: status.name })] }, status.id))) })] })), !isLoading && !hasIssues && (_jsxs("div", { className: "rounded-lg border border-green-200 bg-green-50 p-6 text-center", children: [_jsx(CheckCircle, { className: "mx-auto mb-3 h-12 w-12 text-green-500", strokeWidth: 1 }), _jsx("h3", { className: "mb-1 text-lg font-medium text-green-800", children: "All Systems Operational" }), _jsx("p", { className: "mb-4 text-sm text-green-700", children: "No configuration issues detected. Your Parhelia installation is properly configured." })] })), !isLoading && hasIssues && (_jsxs("div", { className: "space-y-3", children: [issuesBySeverity.errors.map((issue) => (_jsx(IssueCard, { issue: issue, icon: getSeverityIcon(issue.severity), borderClass: getSeverityBorder(issue.severity), onNavigate: handleNavigate }, issue.id))), issuesBySeverity.warnings.map((issue) => (_jsx(IssueCard, { issue: issue, icon: getSeverityIcon(issue.severity), borderClass: getSeverityBorder(issue.severity), onNavigate: handleNavigate }, issue.id))), issuesBySeverity.infos.map((issue) => (_jsx(IssueCard, { issue: issue, icon: getSeverityIcon(issue.severity), borderClass: getSeverityBorder(issue.severity), onNavigate: handleNavigate }, issue.id)))] }))] }) }));
}
/**
 * Individual issue card component
 */
function IssueCard({ issue, icon, borderClass, onNavigate, }) {
    return (_jsxs("div", { className: `flex flex-col items-start gap-2 rounded-lg border p-4 ${borderClass}`, children: [_jsxs("div", { className: "flex items-start gap-2", children: [_jsx("div", { className: "mt-0.5 shrink-0", children: icon }), _jsx("h4", { className: "font-medium text-gray-900", children: issue.title })] }), _jsx("p", { className: "text-sm whitespace-pre-wrap text-gray-600", children: issue.description }), issue.targetPanel && (_jsxs(Button, { size: "sm", variant: "outline", onClick: () => onNavigate(issue), className: "shrink-0", children: [issue.actionLabel || "Fix", _jsx(ArrowRight, { className: "ml-1 h-3 w-3" })] }))] }));
}
export default StatusPanel;
//# sourceMappingURL=StatusPanel.js.map