import { useRef } from "react";
import { Circle } from "react-konva";
import Konva from "konva";
import type { ShapeProps } from "./types";
import { getKonvaGradientProps } from "../../utils/gradient";
import { getKonvaBlurProps, useShapeBlurCache } from "../../utils/shapeBlur";

const CircleShape = ({ obj, isSelected, onSelect, onUpdate, draggable }: ShapeProps) => {
    const shapeRef = useRef<Konva.Circle>(null);

    // Transformer is managed in EditorCanvas for multi-select support

    const isMask = obj.isMask || false;
    const showGuide = obj.showMaskGuide !== false;

    const actualStrokeWidth = obj.strokeWidth ?? 0;
    const hasStroke = actualStrokeWidth > 0;
    const blurProps = isMask ? {} : getKonvaBlurProps(obj.blur);

    useShapeBlurCache(shapeRef, isMask ? 0 : obj.blur, [
        obj.width,
        obj.fill,
        obj.fillType,
        obj.gradient,
        obj.stroke,
        actualStrokeWidth,
        obj.blur,
    ]);

    // برای نمایش انتخاب: اگر strokeWidth واقعی > 0 است، از آن استفاده کن، وگرنه stroke را برای انتخاب نمایش بده
    const displayStroke = isSelected
        ? (hasStroke ? obj.stroke : "#3b82f6")
        : (isMask && showGuide)
            ? "#ff6b6b"
            : (isMask && !showGuide)
                ? "transparent"
                : (hasStroke ? obj.stroke : undefined);

    const displayStrokeWidth = isSelected
        ? (hasStroke ? actualStrokeWidth : 3)
        : (isMask && showGuide ? 2 : actualStrokeWidth);
    const diameter = obj.width || 100;
    const gradientProps = isMask
        ? {}
        : getKonvaGradientProps(obj.fillType, obj.gradient, diameter, diameter, "centered");

    return (
        <Circle
            ref={shapeRef}
            id={obj.id}
            name={isMask ? "mask-shape" : "canvas-object"}
            x={obj.x}
            y={obj.y}
            radius={(obj.width || 50) / 2}
            fill={isMask ? "transparent" : obj.fill}
            {...gradientProps}
            stroke={displayStroke}
            strokeWidth={displayStrokeWidth}
            dash={isMask && showGuide ? [10, 5] : undefined}
            rotation={obj.rotation || 0}
            {...blurProps}
            draggable={draggable}
            onClick={(e) => {
                if (shapeRef.current) {
                    onSelect(obj.id, shapeRef.current, e);
                }
            }}
            onDragMove={(e) => {
                e.target.getLayer()?.batchDraw();
            }}
            onDragEnd={(e) => {
                const node = e.target;
                onUpdate(obj.id, {
                    x: node.x(),
                    y: node.y(),
                });
            }}
        />
    );
};

export default CircleShape;

