import { Group, Text, Transformer } from "react-konva";
import { useRef, useEffect } from "react";
import useEditorStore from "../useEditorStore";

export default function SummaryElement({ element }) {
    const updateElement = useEditorStore((state) => state.updateElement);
    const setSelectedId = useEditorStore((state) => state.setSelectedId);
    const selectedId = useEditorStore((state) => state.selectedId);

    const groupRef = useRef();
    const trRef = useRef();

    const isSelected = selectedId === element.id;

    useEffect(() => {
        if (isSelected && trRef.current && groupRef.current) {
            trRef.current.nodes([groupRef.current]);
            trRef.current.getLayer().batchDraw();
        }
    }, [isSelected]);

    const visibleFields = element.fields.filter((field) => field.visible);

    return (
        <>
            <Group
                ref={groupRef}
                x={element.x}
                y={element.y}
                rotation={element.rotation}
                draggable
                onClick={() => setSelectedId(element.id)}
                onDragEnd={(e) => {
                    const snap = (v) => Math.round(v / 10) * 10;
                    updateElement(element.id, {
                        x: snap(e.target.x()),
                        y: snap(e.target.y()),
                    });
                }}
                onTransformEnd={() => {
                    const node = groupRef.current;
                    updateElement(element.id, {
                        rotation: node.rotation(),
                    });
                }}
            >
                {visibleFields.map((field, index) => {
                    const yPos = index * (element.fontSize + element.spacing);
                    
                    return (
                        <Group key={field.key}>
                            {/* Label */}
                            <Text
                                text={`${field.label}:`}
                                x={0}
                                y={yPos}
                                fontSize={element.fontSize}
                                fill={element.labelColor}
                                fontStyle="bold"
                            />
                            {/* Value placeholder */}
                            <Text
                                text={`{{${field.key}}}`}
                                x={field.width}
                                y={yPos}
                                fontSize={element.fontSize}
                                fill={element.valueColor}
                            />
                        </Group>
                    );
                })}
            </Group>

            {isSelected && (
                <Transformer
                    ref={trRef}
                    enabledAnchors={[]}
                    rotateEnabled={true}
                />
            )}
        </>
    );
}
