import { useEffect, useMemo, useRef } from "react";
import { Rect, Group, Circle, Text as KonvaText } from "react-konva";
import Konva from "konva";
import type { ShapeProps } from "./types";
import { getObjectBorderRadius } from "../../utils/borderRadius";

const AudioShape = ({
    obj,
    isSelected,
    onSelect,
    onUpdate,
    draggable,
}: ShapeProps) => {
    const groupRef = useRef<Konva.Group>(null);
    const labelRef = useRef<Konva.Text>(null);

    const containerWidth = obj.width || 320;
    const containerHeight = obj.height || 56;
    const cornerRadius = getObjectBorderRadius(obj.borderRadius ?? 8);
    const barY = containerHeight * 0.55;
    const barHeight = Math.max(4, containerHeight * 0.12);
    const playRadius = Math.min(18, containerHeight * 0.35);
    const labelWidth = Math.max(0, containerWidth - playRadius * 2 - 44);
    const displayName = useMemo(
        () => obj.audioName?.trim() || "فایل صوتی",
        [obj.audioName],
    );

    useEffect(() => {
        const labelNode = labelRef.current;
        if (!labelNode) return;
        labelNode.text(displayName);
        labelNode.getLayer()?.batchDraw();
    }, [displayName]);

    const handleGroupClick = (e?: Konva.KonvaEventObject<MouseEvent>) => {
        if (e) {
            const target = e.target;
            if (target.hasName("audioControls") || target.getParent()?.hasName("audioControls")) {
                e.cancelBubble = true;
                const evt = e.evt;
                if (evt) {
                    evt.stopPropagation();
                    evt.preventDefault();
                }
                return;
            }
        }
        if (groupRef.current) {
            onSelect(obj.id, groupRef.current, e);
        }
    };

    return (
        <Group
            ref={groupRef}
            id={obj.id}
            x={obj.x}
            y={obj.y}
            rotation={obj.rotation || 0}
            draggable={draggable}
            onClick={handleGroupClick}
            onDragEnd={(e) => {
                const node = e.target;
                onUpdate(obj.id, {
                    x: node.x(),
                    y: node.y(),
                });
            }}
        >
            <Rect
                width={containerWidth}
                height={containerHeight}
                fill="#f3f4f6"
                cornerRadius={cornerRadius}
                stroke={isSelected ? "#3b82f6" : "#d1d5db"}
                strokeWidth={isSelected ? 3 : 1}
                onClick={handleGroupClick}
            />
            <Group name="audioControls" listening={true} onClick={handleGroupClick}>
                <Circle
                    x={playRadius + 12}
                    y={containerHeight / 2}
                    radius={playRadius}
                    fill="#e5e7eb"
                    listening={true}
                />
                <KonvaText
                    x={playRadius + 12}
                    y={containerHeight / 2}
                    text="▶"
                    fontSize={Math.round(playRadius * 0.9)}
                    fill="#9ca3af"
                    fontFamily="Arial"
                    align="center"
                    verticalAlign="middle"
                    offsetX={playRadius * 0.45}
                    offsetY={playRadius * 0.45}
                    listening={false}
                />
            </Group>
            <Rect
                x={playRadius * 2 + 28}
                y={barY}
                width={Math.max(0, containerWidth - playRadius * 2 - 44)}
                height={barHeight}
                fill="#d1d5db"
                cornerRadius={barHeight / 2}
                listening={false}
            />
            <Rect
                x={playRadius * 2 + 28}
                y={barY}
                width={Math.max(0, (containerWidth - playRadius * 2 - 44) * 0.35)}
                height={barHeight}
                fill="#9ca3af"
                cornerRadius={barHeight / 2}
                listening={false}
            />
            <KonvaText
                ref={labelRef}
                key={displayName}
                x={playRadius * 2 + 28}
                y={containerHeight * 0.18}
                text={displayName}
                fontSize={11}
                fill="#6b7280"
                fontFamily="Arial"
                listening={false}
                width={labelWidth}
                ellipsis={true}
            />
        </Group>
    );
};

export default AudioShape;
