import React, { useEffect, useState, } from "react";
import { SpanStatus } from "../../../Models/AnalyticsModels/Span";
import LogSeverity from "../../../Types/Log/LogSeverity";
import FieldLabelElement from "../Detail/FieldLabel";
import Input, { InputType } from "../Input/Input";
const LOG_SEVERITIES = [
    LogSeverity.Fatal,
    LogSeverity.Error,
    LogSeverity.Warning,
    LogSeverity.Information,
    LogSeverity.Debug,
    LogSeverity.Trace,
    LogSeverity.Unspecified,
];
const SPAN_STATUSES = [
    { status: SpanStatus.Error, label: "Error" },
    { status: SpanStatus.Ok, label: "Ok" },
    { status: SpanStatus.Unset, label: "Unset" },
];
const TelemetryRetentionConfigForm = (props) => {
    const [config, setConfig] = useState(props.value || props.initialValue || {});
    useEffect(() => {
        if (props.value) {
            setConfig(props.value);
        }
    }, [props.value]);
    const emit = (next) => {
        setConfig(next);
        if (props.onChange) {
            const isEmpty = !next.logs && !next.traces && !next.metrics && !next.profiles;
            props.onChange(isEmpty ? null : next);
        }
    };
    const parsePositiveOrNull = (raw) => {
        if (!raw || raw.trim() === "") {
            return null;
        }
        const parsed = Number(raw);
        if (!Number.isFinite(parsed) || parsed <= 0) {
            return null;
        }
        return Math.trunc(parsed);
    };
    const setPillarDefault = (pillar, value) => {
        const next = Object.assign({}, config);
        const existing = next[pillar];
        const merged = Object.assign(Object.assign({}, (existing || {})), { default: value });
        // If the only key is `default` and it's null, drop the pillar entirely.
        const keys = Object.keys(merged).filter((k) => {
            return (merged[k] !== null &&
                merged[k] !== undefined);
        });
        if (keys.length === 0) {
            delete next[pillar];
        }
        else {
            next[pillar] = merged;
        }
        emit(next);
    };
    const setLogSeverityValue = (severity, value) => {
        const next = Object.assign({}, config);
        const logs = Object.assign({}, (next.logs || {}));
        const bySeverity = Object.assign({}, (logs.bySeverity || {}));
        if (value === null) {
            delete bySeverity[severity];
        }
        else {
            bySeverity[severity] = value;
        }
        if (Object.keys(bySeverity).length === 0) {
            delete logs.bySeverity;
        }
        else {
            logs.bySeverity = bySeverity;
        }
        if (Object.keys(logs).length === 0) {
            delete next.logs;
        }
        else {
            next.logs = logs;
        }
        emit(next);
    };
    const setSpanStatusValue = (status, value) => {
        const next = Object.assign({}, config);
        const traces = Object.assign({}, (next.traces || {}));
        const byStatus = Object.assign({}, (traces.byStatus || {}));
        if (value === null) {
            delete byStatus[status];
        }
        else {
            byStatus[status] = value;
        }
        if (Object.keys(byStatus).length === 0) {
            delete traces.byStatus;
        }
        else {
            traces.byStatus = byStatus;
        }
        if (Object.keys(traces).length === 0) {
            delete next.traces;
        }
        else {
            next.traces = traces;
        }
        emit(next);
    };
    const numberToString = (value) => {
        return typeof value === "number" && value > 0 ? String(value) : "";
    };
    const renderPillarDefault = (pillar, label, description) => {
        var _a;
        return (React.createElement("div", { className: "mb-4" },
            React.createElement(FieldLabelElement, { title: label, description: description }),
            React.createElement(Input, { type: InputType.NUMBER, placeholder: "Use default retention", value: numberToString((_a = config[pillar]) === null || _a === void 0 ? void 0 : _a.default), onChange: (raw) => {
                    setPillarDefault(pillar, parsePositiveOrNull(raw));
                } })));
    };
    return (React.createElement("div", { className: "space-y-6" },
        React.createElement("div", { className: "rounded-md border border-gray-200 dark:border-slate-700 p-4" },
            React.createElement("h3", { className: "text-sm font-semibold text-gray-900 dark:text-slate-100 mb-1" }, "Logs"),
            React.createElement("p", { className: "text-xs text-gray-500 dark:text-slate-400 mb-3" }, "Retention in days for log records. Per-severity values take precedence over the logs default; leave any field blank to fall back."),
            renderPillarDefault("logs", "Logs default (days)", "Applies to every log record unless its severity has a specific override below."),
            React.createElement("div", { className: "border-t border-gray-100 dark:border-slate-800 pt-3 mt-2" },
                React.createElement("p", { className: "text-xs font-medium text-gray-700 dark:text-slate-300 mb-2" }, "Per-severity overrides"),
                React.createElement("div", { className: "grid grid-cols-1 sm:grid-cols-2 gap-3" }, LOG_SEVERITIES.map((severity) => {
                    var _a, _b;
                    return (React.createElement("div", { key: severity },
                        React.createElement(FieldLabelElement, { title: severity }),
                        React.createElement(Input, { type: InputType.NUMBER, placeholder: "Use logs default", value: numberToString((_b = (_a = config.logs) === null || _a === void 0 ? void 0 : _a.bySeverity) === null || _b === void 0 ? void 0 : _b[severity]), onChange: (raw) => {
                                setLogSeverityValue(severity, parsePositiveOrNull(raw));
                            } })));
                })))),
        React.createElement("div", { className: "rounded-md border border-gray-200 dark:border-slate-700 p-4" },
            React.createElement("h3", { className: "text-sm font-semibold text-gray-900 dark:text-slate-100 mb-1" }, "Traces"),
            React.createElement("p", { className: "text-xs text-gray-500 dark:text-slate-400 mb-3" }, "Retention in days for spans and the exceptions captured on them. Per-status values take precedence over the traces default."),
            renderPillarDefault("traces", "Traces default (days)", "Applies to every span unless its status has a specific override below."),
            React.createElement("div", { className: "border-t border-gray-100 dark:border-slate-800 pt-3 mt-2" },
                React.createElement("p", { className: "text-xs font-medium text-gray-700 dark:text-slate-300 mb-2" }, "Per-status overrides"),
                React.createElement("div", { className: "grid grid-cols-1 sm:grid-cols-3 gap-3" }, SPAN_STATUSES.map((entry) => {
                    var _a, _b;
                    return (React.createElement("div", { key: entry.label },
                        React.createElement(FieldLabelElement, { title: entry.label }),
                        React.createElement(Input, { type: InputType.NUMBER, placeholder: "Use traces default", value: numberToString((_b = (_a = config.traces) === null || _a === void 0 ? void 0 : _a.byStatus) === null || _b === void 0 ? void 0 : _b[entry.status]), onChange: (raw) => {
                                setSpanStatusValue(entry.status, parsePositiveOrNull(raw));
                            } })));
                })))),
        React.createElement("div", { className: "rounded-md border border-gray-200 dark:border-slate-700 p-4" },
            React.createElement("h3", { className: "text-sm font-semibold text-gray-900 dark:text-slate-100 mb-1" }, "Metrics"),
            React.createElement("p", { className: "text-xs text-gray-500 dark:text-slate-400 mb-3" }, "Retention in days for metric data points."),
            renderPillarDefault("metrics", "Metrics default (days)", "Applies to all metric points. Leave blank to use the default retention.")),
        React.createElement("div", { className: "rounded-md border border-gray-200 dark:border-slate-700 p-4" },
            React.createElement("h3", { className: "text-sm font-semibold text-gray-900 dark:text-slate-100 mb-1" }, "Profiles"),
            React.createElement("p", { className: "text-xs text-gray-500 dark:text-slate-400 mb-3" }, "Retention in days for profile samples."),
            renderPillarDefault("profiles", "Profiles default (days)", "Applies to all profile samples. Leave blank to use the default retention."))));
};
export default TelemetryRetentionConfigForm;
//# sourceMappingURL=TelemetryRetentionConfigForm.js.map