import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useCallback, useState, useEffect, useMemo } from "react";
import { Button } from "../../../components/ui/button";
import { SettingsCard as Card } from "../SettingsCard";
import { Alert, AlertDescription, AlertTitle, } from "../../../components/ui/alert";
import { SettingsPanelLayout } from "../SettingsPanelLayout";
import { useEditContext } from "../../client/editContext";
import { LoadingState } from "../../ui/LoadingState";
import { getSystemStatus } from "../../services/systemService";
import { CheckCircle, AlertCircle, AlertTriangle, Database, 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 [systemStatus, setSystemStatus] = useState(null);
    const [systemStatusError, setSystemStatusError] = useState(null);
    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,
        })));
        const statusResult = await getSystemStatus({
            force: options?.refreshSystemStatusFirst === true,
        });
        if (statusResult.type === "success") {
            setSystemStatus(statusResult.data ?? null);
            setSystemStatusError(null);
        }
        else {
            setSystemStatusError(statusResult.summary ||
                statusResult.details ||
                "Unable to load database details");
        }
        // 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: "text-feedback-red h-5 w-5", strokeWidth: 1 }));
            case "warning":
                return (_jsx(AlertTriangle, { className: "text-feedback-orange h-5 w-5", strokeWidth: 1 }));
            case "info":
                return _jsx(Info, { className: "text-feedback-blue h-5 w-5", strokeWidth: 1 });
        }
    };
    const getAlertVariant = (severity) => {
        switch (severity) {
            case "error":
                return "destructive";
            case "warning":
                return "warning";
            case "info":
                return "info";
        }
    };
    const isLoading = overallState === "loading";
    const hasIssues = allIssues.length > 0;
    const parheliaDatabase = systemStatus?.parheliaDatabase;
    const issuesSummary = `${allIssues.length} issue${allIssues.length !== 1 ? "s" : ""} found${issuesBySeverity.errors.length > 0
        ? ` (${issuesBySeverity.errors.length} error${issuesBySeverity.errors.length !== 1 ? "s" : ""})`
        : ""}`;
    return (_jsxs(SettingsPanelLayout, { contentClassName: "flex flex-col gap-4", children: [(isLoading || hasIssues) && (_jsx("div", { className: "flex items-center gap-3", children: isLoading ? (_jsx(LoadingState, { variant: "inline", message: "Running status checks...", spinnerClassName: "text-feedback-orange", spinnerSize: "md" })) : hasIssues ? (_jsxs(_Fragment, { children: [_jsx(AlertTriangle, { className: "text-feedback-orange h-5 w-5", strokeWidth: 1 }), _jsxs("span", { className: "text-neutral-grey-50 text-sm", children: [allIssues.length, " issue", allIssues.length !== 1 ? "s" : "", " ", "found", issuesBySeverity.errors.length > 0 && (_jsxs("span", { className: "text-feedback-red ml-1", children: ["(", issuesBySeverity.errors.length, " error", issuesBySeverity.errors.length !== 1 ? "s" : "", ")"] }))] })] })) : null })), _jsx(Card, { icon: _jsx(Database, { className: "h-5 w-5", strokeWidth: 1 }), title: "Parhelia database", description: "Current SQL connection used for Parhelia system data.", children: systemStatusError ? (_jsx("p", { className: "text-feedback-red text-sm", children: systemStatusError })) : (_jsxs("dl", { className: "grid gap-4 sm:grid-cols-2", children: [_jsx(DatabaseDetail, { label: "Database", value: parheliaDatabase?.databaseName }), _jsx(DatabaseDetail, { label: "Server", value: parheliaDatabase?.serverName }), _jsx(DatabaseDetail, { label: "Connection", value: parheliaDatabase?.connectionStringName })] })) }), isLoading && (_jsxs("div", { className: "border-border-default bg-neutral-grey-5 space-y-2 rounded-lg border p-4", children: [_jsx("div", { className: "text-neutral-grey-100 text-sm font-medium", 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, { strokeWidth: 1, className: "text-feedback-orange h-3 w-3 animate-spin" })) : status.state === "success" ? (_jsx(CheckCircle, { strokeWidth: 1, className: "text-feedback-green h-3 w-3" })) : (_jsx(AlertCircle, { strokeWidth: 1, className: "text-feedback-red h-3 w-3" })), _jsx("span", { className: "text-neutral-grey-50", children: status.name })] }, status.id))) })] })), !isLoading && !hasIssues && (_jsxs("div", { className: "border-feedback-green bg-feedback-green-light rounded-lg border p-6 text-center", children: [_jsx(CheckCircle, { className: "text-feedback-green mx-auto mb-3 h-12 w-12", strokeWidth: 1 }), _jsx("h3", { className: "text-feedback-green mb-1 text-lg font-medium", children: "All systems operational" }), _jsx("p", { className: "text-feedback-green mb-4 text-sm", children: "No configuration issues detected. Your Parhelia installation is properly configured." })] })), !isLoading && hasIssues && (_jsx(Card, { icon: _jsx(AlertTriangle, { className: "text-feedback-orange h-5 w-5", strokeWidth: 1 }), title: "Detected issues", description: issuesSummary, children: _jsxs("div", { className: "space-y-3", children: [issuesBySeverity.errors.map((issue) => (_jsx(IssueCard, { issue: issue, icon: getSeverityIcon(issue.severity), variant: getAlertVariant(issue.severity), onNavigate: handleNavigate }, issue.id))), issuesBySeverity.warnings.map((issue) => (_jsx(IssueCard, { issue: issue, icon: getSeverityIcon(issue.severity), variant: getAlertVariant(issue.severity), onNavigate: handleNavigate }, issue.id))), issuesBySeverity.infos.map((issue) => (_jsx(IssueCard, { issue: issue, icon: getSeverityIcon(issue.severity), variant: getAlertVariant(issue.severity), onNavigate: handleNavigate }, issue.id)))] }) }))] }));
}
function DatabaseDetail({ label, value }) {
    const displayValue = value?.trim() || "Not available";
    return (_jsxs("div", { className: "min-w-0", children: [_jsx("dt", { className: "text-neutral-grey-50 text-xs font-medium", children: label }), _jsx("dd", { className: "text-neutral-grey-100 mt-1 truncate font-mono text-sm", title: displayValue, children: displayValue })] }));
}
/**
 * Individual issue card component
 */
function IssueCard({ issue, icon, variant, onNavigate, }) {
    return (_jsxs(Alert, { variant: variant, className: "p-4", children: [icon, _jsxs("div", { className: "flex flex-col items-start gap-2", children: [_jsx(AlertTitle, { className: "text-neutral-grey-100 mb-0", children: issue.title }), _jsx(AlertDescription, { className: `whitespace-pre-wrap ${issue.severity === "warning"
                            ? "text-neutral-grey-100"
                            : "text-neutral-grey-50"}`, children: issue.description }), issue.targetPanel && (_jsxs(Button, { size: "sm", variant: "outline", onClick: () => onNavigate(issue), className: "shrink-0", children: [issue.actionLabel || "Fix", _jsx(ArrowRight, { strokeWidth: 1, className: "ml-1 h-3 w-3" })] }))] })] }));
}
export default StatusPanel;
//# sourceMappingURL=StatusPanel.js.map