import React, { useMemo, useCallback, useRef, useState, } from "react";
import { BarChart, Bar, XAxis, YAxis, Tooltip, ResponsiveContainer, ReferenceArea, } from "recharts";
import { getSeverityColor, getAllSeverityKeys, } from "./severityColors";
import HistogramTooltip from "./HistogramTooltip";
import ComponentLoader from "../../ComponentLoader/ComponentLoader";
import OneUptimeDate from "../../../../Types/Date";
function pivotBuckets(buckets) {
    const map = new Map();
    for (const bucket of buckets) {
        let row = map.get(bucket.time);
        if (!row) {
            row = { time: bucket.time };
            map.set(bucket.time, row);
        }
        row[bucket.severity] =
            (row[bucket.severity] || 0) + bucket.count;
    }
    return Array.from(map.values());
}
function formatTickTime(time) {
    const date = OneUptimeDate.fromString(time);
    if (isNaN(date.getTime())) {
        return time;
    }
    return date.toLocaleTimeString([], {
        hour: "2-digit",
        minute: "2-digit",
        hour12: false,
    });
}
function formatYAxisTick(value) {
    if (value >= 1000000) {
        return `${(value / 1000000).toFixed(1)}M`;
    }
    if (value >= 1000) {
        return `${(value / 1000).toFixed(value >= 10000 ? 0 : 1)}K`;
    }
    return value.toString();
}
const LogsHistogram = (props) => {
    const [selectionStart, setSelectionStart] = useState(null);
    const [selectionEnd, setSelectionEnd] = useState(null);
    const isSelecting = useRef(false);
    const pivotedData = useMemo(() => {
        return pivotBuckets(props.buckets);
    }, [props.buckets]);
    const activeSeverities = useMemo(() => {
        const present = new Set();
        for (const bucket of props.buckets) {
            present.add(bucket.severity);
        }
        return getAllSeverityKeys().filter((key) => {
            return present.has(key);
        });
    }, [props.buckets]);
    const handleMouseDown = useCallback((e) => {
        if (!props.onTimeRangeSelect || !(e === null || e === void 0 ? void 0 : e.activeLabel)) {
            return;
        }
        isSelecting.current = true;
        setSelectionStart(e.activeLabel);
        setSelectionEnd(null);
    }, [props.onTimeRangeSelect]);
    const handleMouseMove = useCallback((e) => {
        if (!isSelecting.current || !(e === null || e === void 0 ? void 0 : e.activeLabel)) {
            return;
        }
        setSelectionEnd(e.activeLabel);
    }, []);
    const handleMouseUp = useCallback(() => {
        if (!isSelecting.current ||
            !selectionStart ||
            !selectionEnd ||
            !props.onTimeRangeSelect) {
            isSelecting.current = false;
            setSelectionStart(null);
            setSelectionEnd(null);
            return;
        }
        isSelecting.current = false;
        const start = OneUptimeDate.fromString(selectionStart);
        const end = OneUptimeDate.fromString(selectionEnd);
        if (isNaN(start.getTime()) || isNaN(end.getTime())) {
            setSelectionStart(null);
            setSelectionEnd(null);
            return;
        }
        const earlierDate = start < end ? start : end;
        const laterDate = start < end ? end : start;
        props.onTimeRangeSelect(earlierDate, laterDate);
        setSelectionStart(null);
        setSelectionEnd(null);
    }, [selectionStart, selectionEnd, props.onTimeRangeSelect]);
    if (props.isLoading && pivotedData.length === 0) {
        return (React.createElement("div", { className: "flex h-32 items-center justify-center rounded-lg border border-gray-200 bg-white" },
            React.createElement(ComponentLoader, null)));
    }
    if (pivotedData.length === 0) {
        return React.createElement(React.Fragment, null);
    }
    return (React.createElement("div", { className: "rounded-lg border border-gray-200 bg-white" },
        React.createElement("div", { className: "flex items-center justify-between border-b border-gray-100 px-4 py-2" },
            React.createElement("div", { className: "flex items-center gap-2" },
                React.createElement("span", { className: "text-xs font-medium text-gray-500" }, "Log Volume"),
                props.onTimeRangeSelect && (React.createElement("span", { className: "text-[10px] text-gray-300" }, "Drag to zoom"))),
            React.createElement("div", { className: "flex items-center gap-3" }, activeSeverities.map((severity) => {
                const color = getSeverityColor(severity);
                return (React.createElement("div", { key: severity, className: "flex items-center gap-1.5" },
                    React.createElement("span", { className: "inline-block h-2.5 w-2.5 rounded-sm", style: { backgroundColor: color.fill } }),
                    React.createElement("span", { className: "text-[11px] text-gray-500" }, color.label)));
            }))),
        React.createElement("div", { className: "px-2 pb-1 pt-2", style: {
                height: 120,
                cursor: props.onTimeRangeSelect ? "crosshair" : "default",
            } },
            React.createElement(ResponsiveContainer, { width: "100%", height: "100%" },
                React.createElement(BarChart, { data: pivotedData, margin: { top: 4, right: 8, bottom: 0, left: -4 }, onMouseDown: handleMouseDown, onMouseMove: handleMouseMove, onMouseUp: handleMouseUp, barCategoryGap: "15%", barGap: 0 },
                    React.createElement(XAxis, { dataKey: "time", tickFormatter: formatTickTime, tick: { fontSize: 10, fill: "#9ca3af" }, axisLine: { stroke: "#e5e7eb" }, tickLine: false, minTickGap: 40, dy: 4, interval: "preserveStartEnd" }),
                    React.createElement(YAxis, { tick: { fontSize: 10, fill: "#9ca3af" }, axisLine: false, tickLine: false, width: 48, allowDecimals: false, tickFormatter: formatYAxisTick }),
                    React.createElement(Tooltip, { content: React.createElement(HistogramTooltip, null), cursor: { fill: "rgba(99,102,241,0.06)" } }),
                    activeSeverities.map((severity, index) => {
                        const isLast = index === activeSeverities.length - 1;
                        return (React.createElement(Bar, { key: severity, dataKey: severity, stackId: "severity", fill: getSeverityColor(severity).fill, radius: isLast ? [1.5, 1.5, 0, 0] : [0, 0, 0, 0], isAnimationActive: false, maxBarSize: 24 }));
                    }),
                    selectionStart && selectionEnd && (React.createElement(ReferenceArea, { x1: selectionStart, x2: selectionEnd, fill: "rgba(99,102,241,0.12)", stroke: "rgba(99,102,241,0.5)", strokeWidth: 1, radius: 2 })))))));
};
export default LogsHistogram;
//# sourceMappingURL=LogsHistogram.js.map