import { useEffect, useRef, useState } from '@wordpress/element';
import { Popover } from '@wordpress/components';
import * as d3 from 'd3';

const BarGraph = ({ 
    chartData = [], 
    height = '400px', 
    width = '100%', 
    valueColumn = 'Value',
    labelsColumn = 'Label',
    colorColumn = 'Color',
    popoverColumn = 'Content',
    defaultBarColor = '#4CAF50'
}) => {
    const d3Container = useRef(null);
    const [activePopover, setActivePopover] = useState(null);

    useEffect(() => {
        if (!Array.isArray(chartData) || chartData.length === 0 || !d3Container.current) {
            return;
        }

        // Get the first row to determine fields
        const firstRow = chartData[0];
        const fields = Object.keys(firstRow);
        if (fields.length < 2) return;

        // Clear any existing SVG
        d3.select(d3Container.current).selectAll('*').remove();

        // Set the dimensions and margins of the graph
        const margin = { top: 30, right: 30, bottom: 70, left: 60 };
        const containerWidth = d3Container.current.clientWidth;
        const containerHeight = parseInt(height) || 400;
        const graphWidth = containerWidth - margin.left - margin.right;
        const graphHeight = containerHeight - margin.top - margin.bottom;

        // Create the SVG container
        const svg = d3.select(d3Container.current)
            .append('svg')
            .attr('width', containerWidth)
            .attr('height', containerHeight)
            .append('g')
            .attr('transform', `translate(${margin.left},${margin.top})`);

        // X axis
        const x = d3.scaleBand()
            .range([0, graphWidth])
            .domain(chartData.map(d => String(d[labelsColumn])))
            .padding(0.2);

        svg.append('g')
            .attr('transform', `translate(0,${graphHeight})`)
            .call(d3.axisBottom(x))
            .selectAll('text')
            .attr('transform', 'translate(-10,0)rotate(-45)')
            .style('text-anchor', 'end');

        // Add X axis label
        svg.append('text')
            .attr('text-anchor', 'middle')
            .attr('x', graphWidth / 2)
            .attr('y', graphHeight + margin.bottom - 10)
            .text(labelsColumn);

        // Y axis
        const y = d3.scaleLinear()
            .domain([0, d3.max(chartData, d => {
                const val = Number(d[valueColumn]);
                return isNaN(val) ? 0 : val;
            })])
            .range([graphHeight, 0]);

        svg.append('g')
            .call(d3.axisLeft(y));

        // Add Y axis label
        svg.append('text')
            .attr('text-anchor', 'middle')
            .attr('transform', 'rotate(-90)')
            .attr('y', -margin.left + 20)
            .attr('x', -graphHeight / 2)
            .text(valueColumn);

        // Add the bars
        svg.selectAll('rect')
            .data(chartData)
            .join('rect')
            .attr('x', d => x(String(d[labelsColumn])))
            .attr('y', d => {
                const val = Number(d[valueColumn]);
                return y(isNaN(val) ? 0 : val);
            })
            .attr('width', x.bandwidth())
            .attr('height', d => {
                const val = Number(d[valueColumn]);
                return graphHeight - y(isNaN(val) ? 0 : val);
            })
            .attr('fill', d => colorColumn && d[colorColumn] ? d[colorColumn] : defaultBarColor)
            .on('mouseover', function(event, d) {
                // Highlight the bar
                d3.select(this)
                    .transition()
                    .duration(200)
                    .attr('opacity', 0.8);

                // Show value label
                svg.append('text')
                    .attr('class', 'value-label')
                    .attr('x', x(String(d[labelsColumn])) + x.bandwidth() / 2)
                    .attr('y', y(Number(d[valueColumn])) - 5)
                    .attr('text-anchor', 'middle')
                    .text(d[valueColumn]);

                // Show popover if content exists
                if (popoverColumn && d[popoverColumn]) {
                    const rect = this.getBoundingClientRect();
                    setActivePopover({
                        content: d[popoverColumn],
                        position: {
                            top: rect.top + window.scrollY,
                            left: rect.left + rect.width / 2 + window.scrollX,
                        }
                    });
                }
            })
            .on('mouseout', function() {
                // Remove highlight
                d3.select(this)
                    .transition()
                    .duration(200)
                    .attr('opacity', 1);
                
                // Remove value label
                svg.selectAll('.value-label').remove();

                // Hide popover
                setActivePopover(null);
            });

    }, [chartData, height, width, valueColumn, labelsColumn, colorColumn, popoverColumn, defaultBarColor]);

    return (
        <div style={{ position: 'relative' }}>
            <div 
                className="d3-container"
                ref={d3Container}
                style={{ 
                    width: width,
                    height: height,
                    backgroundColor: '#ffffff'
                }}
            />
            {activePopover && (
                <Popover
                    position="top"
                    focusOnMount={false}
                    onClose={() => setActivePopover(null)}
                    anchorRect={{
                        top: activePopover.position.top,
                        left: activePopover.position.left,
                        bottom: activePopover.position.top,
                        right: activePopover.position.left,
                        width: 0,
                        height: 0,
                    }}
                >
                    <div 
                        style={{ padding: '12px' }}
                        dangerouslySetInnerHTML={{ __html: activePopover.content }}
                    />
                </Popover>
            )}
        </div>
    );
};

export default BarGraph;
