import ReactECharts from "echarts-for-react";
import { useRef, useState, useEffect } from "react";
import eventBus from "../util/EventBus.jsx";
import "./TimelineStacked.css"; // We'll create this CSS file

function TimelineStacked({ prompt, data, msg_bus_topic, onDelete }) {
    const chartRef = useRef(null);
    const [markerValue, setMarkerValue] = useState(0.0);
    const unsubscribeRef = useRef(null);

    // Calculate min and max x values from data
    // Sort data by x values and calculate min/max
    const getSortedDataAndLimits = () => {
        if (!data || !data["data"] || data["data"].length === 0) {
            return {
                sortedData: [],
                min: 0,
                max: 100,
            };
        }

        // Sort data by x values (first element of each point)
        const sortedData = [...data["data"]].sort((a, b) => a[0] - b[0]);

        const xValues = sortedData.map((point) => point[0]);
        return {
            sortedData: sortedData,
            min: Math.min(...xValues),
            max: Math.max(...xValues),
        };
    };

    const { sortedData, min, max } = getSortedDataAndLimits();

    useEffect(() => {
        // Subscribe and store the unsubscribe function
        const { unSubscribe } = eventBus.subscribe(msg_bus_topic, (obj) => {
            setMarkerValue(obj["time"]);
        });
        
        unsubscribeRef.current = unSubscribe;

        return () => {
            if (unsubscribeRef.current) {
                unsubscribeRef.current();
            }
        };
    }, [msg_bus_topic]);

    const handleDelete = () => {
        // Unsubscribe from event bus to prevent memory leaks
        if (unsubscribeRef.current) {
            unsubscribeRef.current();
        }
        
        // Call parent's delete handler
        if (onDelete) {
            onDelete();
        }
    };

    const option = {
        animation: false,
        grid: {
            left: 0,
            right: 0,
            top: 20, // Add space for the delete button
            bottom: 0,
            containLabel: false,
        },
        graphic: [
            {
                type: "text",
                left: 0,
                top: 0,
                style: {
                    text: prompt || "",
                    fontSize: 12,
                    fontWeight: "bold",
                    fill: "#FFFFFFF0",
                    backgroundColor: "rgba(255, 255, 255, 0.1)",
                    padding: [4, 8],
                    borderRadius: 4,
                },
                z: 100,
            },
        ],
        xAxis: {
            type: "value",
            min: min,
            max: max,
            show: false,
            axisLine: { show: false },
            axisTick: { show: false },
            axisLabel: { show: false },
            splitLine: { show: false },
        },
        yAxis: {
            type: "value",
            show: true,
            axisLine: { show: false },
            axisTick: { show: false },
            axisLabel: { show: true },
            splitLine: { show: false },
        },
        series: [
            {
                type: "line",
                symbol: "none",
                lineStyle: { width: 1, opacity: 1 },
                data: sortedData,
                smooth: false,
                z: 4,
                markLine: {
                    symbol: "none",
                    lineStyle: {
                        color: "#ff4757",
                        width: 2,
                        type: "solid",
                    },
                    data: [
                        {
                            xAxis: markerValue,
                            label: {
                                show: false,
                            },
                        },
                    ],
                },
            },
        ],
    };

    return (
        <div className="timeline-stacked-container">
            <button 
                className="delete-timeline-btn" 
                onClick={handleDelete}
                title="Delete this timeline"
            >
                ×
            </button>
            <ReactECharts
                ref={chartRef}
                option={option}
                style={{ width: "100%", height: "100%" }}
            />
        </div>
    );
}

export default TimelineStacked;
