import React, { useRef, useEffect } from "react";
import * as d3 from "d3";
import { getStatusColor } from "./dataUtils";

const TreeChart = ({ data, onNodeClick }) => {
    const chartRef = useRef();

    useEffect(() => {
        if (!data || !data.items) return;

        const width = 1000;
        const height = 1000;

        const root = d3.hierarchy(data, (d) => d.items);
        const links = root.links();
        const nodes = root.descendants();

        const svg = d3.select(chartRef.current);
        svg.selectAll("*").remove();

        svg
            .attr("width", width)
            .attr("height", height)
            .attr("viewBox", [-width / 2, -height / 2, width, height])
            .attr("style", "max-width: 100%; height: auto;");

        const link = svg.append("g")
            .attr("stroke", "#999")
            .attr("stroke-opacity", 0.6)
            .selectAll("line")
            .data(links)
            .join("line"); // Используем join для обновления связей

        const node = svg.append("g")
            .attr("stroke", "#000")
            .attr("stroke-width", 1.5)
            .selectAll("circle")
            .data(nodes)
            .join("circle")  // Используем join для обновления узлов
            .attr("fill", (d) => getStatusColor(d.data.status))
            .attr("stroke", "#fff")
            .attr("r", 7)
            .call(drag());

        // Обновляем только те узлы, которые нуждаются в изменении
        node.each(function (d) {
            if (d.data.status === "red") {
                d3.select(this)
                    .transition()
                    .duration(500)
                    .ease(d3.easeLinear)
                    .style("opacity", 0.3)
                    .transition()
                    .duration(500)
                    .ease(d3.easeLinear)
                    .style("opacity", 1)
                    .on("end", function repeat() {
                        d3.select(this)
                            .transition()
                            .duration(500)
                            .ease(d3.easeLinear)
                            .style("opacity", 0.3)
                            .transition()
                            .duration(500)
                            .ease(d3.easeLinear)
                            .style("opacity", 1)
                            .on("end", repeat);
                    });
            }
        });

        const text = svg.append("g")
            .attr("fill", "#000")
            .attr("font-family", "Arial")
            .attr("font-size", 12)
            .attr("pointer-events", "none")
            .selectAll("text")
            .data(nodes)
            .join("text")
            .text((d) => d.data.title)
            .attr("dx", 12)
            .attr("dy", 4);

        node.append("title").text((d) => d.data.title);

        node.on("click", (event, d) => {
            if (onNodeClick) {
                onNodeClick(d.data.id, d.data.title);
            }
        });

        const simulation = d3.forceSimulation(nodes)
            .force("link", d3.forceLink(links).id((d) => d.data.title).distance(80).strength(1))
            .force("charge", d3.forceManyBody().strength(-500))
            .force("x", d3.forceX())
            .force("y", d3.forceY());

        simulation.on("tick", () => {
            link
                .attr("x1", (d) => d.source.x)
                .attr("y1", (d) => d.source.y)
                .attr("x2", (d) => d.target.x)
                .attr("y2", (d) => d.target.y);

            node
                .attr("cx", (d) => d.x)
                .attr("cy", (d) => d.y);

            text
                .attr("x", (d) => d.x + 12)
                .attr("y", (d) => d.y + 4);
        });

        return () => simulation.stop();
    }, [data, onNodeClick]);

    const drag = () => {
        function dragstarted(event, d) {
            d.fx = d.x;
            d.fy = d.y;
        }

        function dragged(event, d) {
            d.fx = event.x;
            d.fy = event.y;
        }

        function dragended(event, d) {
            d.fx = null;
            d.fy = null;
        }

        return d3.drag().on("start", dragstarted).on("drag", dragged).on("end", dragended);
    };

    return <svg ref={chartRef}></svg>;
};

export default TreeChart;
