import { useEffect, useRef } from "react";
import { Text } from "react-konva";
import Konva from "konva";
import type { TextShapeProps } from "./types";

const TextShape = ({
  obj,
  isSelected,
  transformerRef,
  onSelect,
  onUpdate,
  draggable,
  layerRef,
}: TextShapeProps) => {
  const shapeRef = useRef<Konva.Text>(null);

  useEffect(() => {
    if (isSelected && shapeRef.current && transformerRef.current) {
      transformerRef.current.nodes([shapeRef.current]);
      transformerRef.current.getLayer()?.batchDraw();
    }
  }, [isSelected, transformerRef]);

  return (
    <Text
      ref={shapeRef}
      x={obj.x}
      y={obj.y}
      text={obj.text || ""}
      fontSize={obj.fontSize || 24}
      fill={obj.fill || "#000000"}
      fontFamily="irancell"
      width={obj.width}
      height={obj.height}
      rotation={obj.rotation || 0}
      draggable={draggable}
      onClick={() => {
        if (shapeRef.current) {
          onSelect(obj.id, shapeRef.current);
        }
      }}
      onDragEnd={(e) => {
        const node = e.target;
        onUpdate(obj.id, {
          x: node.x(),
          y: node.y(),
        });
      }}
      onTransformEnd={() => {
        const node = shapeRef.current;
        if (!node) return;

        const scaleX = node.scaleX();
        const scaleY = node.scaleY();

        node.scaleX(1);
        node.scaleY(1);

        onUpdate(obj.id, {
          x: node.x(),
          y: node.y(),
          rotation: node.rotation(),
          width: obj.width ? Math.max(5, obj.width * scaleX) : undefined,
          height: obj.height ? Math.max(5, obj.height * scaleY) : undefined,
        });
      }}
      onDblClick={(e) => {
        const textNode = e.target as Konva.Text;
        const stage = textNode.getStage();
        if (!stage) return;

        const textPosition = textNode.absolutePosition();
        const areaPosition = {
          x: stage.container().offsetLeft + textPosition.x,
          y: stage.container().offsetTop + textPosition.y,
        };

        const textarea = document.createElement("textarea");
        document.body.appendChild(textarea);
        textarea.value = textNode.text();
        textarea.style.position = "absolute";
        textarea.style.top = `${areaPosition.y}px`;
        textarea.style.left = `${areaPosition.x}px`;
        textarea.style.width = `${textNode.width()}px`;
        textarea.style.fontSize = `${textNode.fontSize()}px`;
        textarea.style.border = "none";
        textarea.style.padding = "0px";
        textarea.style.margin = "0px";
        textarea.style.overflow = "hidden";
        textarea.style.background = "transparent";
        textarea.style.outline = "none";
        textarea.style.resize = "none";
        textarea.style.fontFamily = "irancell";
        textarea.style.direction = "rtl";
        textarea.focus();

        const removeTextarea = () => {
          document.body.removeChild(textarea);
          textNode.text(textarea.value);
          onUpdate(obj.id, { text: textarea.value });
          layerRef.current?.draw();
        };

        textarea.addEventListener("keydown", (e) => {
          if (e.key === "Enter" && !e.shiftKey) {
            removeTextarea();
          }
          if (e.key === "Escape") {
            removeTextarea();
          }
        });

        textarea.addEventListener("blur", () => {
          removeTextarea();
        });
      }}
    />
  );
};

export default TextShape;

