import { useEffect, useRef } from "react";
import { Stage, Layer, Rect } from "react-konva";
import Konva from "konva";
import { useEditorStore } from "../store/editorStore";
import { useDrawingHandlers } from "./canvas/useDrawingHandlers";
import { useStageSize } from "./canvas/useStageSize";
import { useKeyboardMovement } from "./canvas/useKeyboardMovement";
import { useSelectionHandlers } from "./canvas/useSelectionHandlers";
import { useTransformHandlers } from "./canvas/useTransformHandlers";
import { useObjectHandlers } from "./canvas/useObjectHandlers";
import { useMaskGroupState } from "./canvas/useMaskGroupState";
import ObjectsLayer from "./canvas/ObjectsLayer";
import CellEditor from "@/components/CellEditor";
import ZoomControls from "./ZoomControls";

type EditorCanvasProps = {
  catalogSize?: string;
};

const EditorCanvas = ({ catalogSize }: EditorCanvasProps) => {
  const stageRef = useRef<Konva.Stage>(null);
  const layerRef = useRef<Konva.Layer>(null);

  const {
    tool,
    objects,
    selectedObjectId,
    selectedObjectIds,
    selectedCellId,
    editingCell,
    setStageRef,
    setLayerRef,
    zoom,
  } = useEditorStore();

  const { transformerRef, handleStageMouseDown, handleStageMouseMove, handleStageMouseUp } = useDrawingHandlers();
  const stageSize = useStageSize(catalogSize);
  useKeyboardMovement();

  const { handleSelect, handleCellClick, handleCellDblClick } = useSelectionHandlers();
  const { handleObjectUpdate, handleGroupWithMask, handleUngroupFromMask, handleCellEditorSave, handleCellEditorCancel } =
    useObjectHandlers();

  const { isGroupedWithMask, maskObject, canGroup, canUngroup, selectedObject } = useMaskGroupState(selectedObjectId);

  useTransformHandlers(transformerRef, layerRef);

  useEffect(() => {
    if (stageRef.current) {
      setStageRef(stageRef);
    }
    if (layerRef.current) {
      setLayerRef(layerRef);
    }
  }, [setStageRef, setLayerRef]);


  const finalScale = stageSize.scale * zoom;

  return (
    <div className="flex-1 flex items-center justify-center pb-8 overflow-auto relative">
      <div className="shadow-lg mt-8">
        <Stage
          ref={stageRef}
          width={stageSize.width * finalScale}
          height={stageSize.height * finalScale}
          scaleX={finalScale}
          scaleY={finalScale}
          onMouseDown={handleStageMouseDown}
          onMouseMove={handleStageMouseMove}
          onMouseUp={handleStageMouseUp}
        >
          <Layer listening={false}>
            <Rect
              x={0}
              y={0}
              width={stageSize.width}
              height={stageSize.height}
              fill="#ffffff"
              listening={false}
            />
          </Layer>

          <ObjectsLayer
            layerRef={layerRef}
            objects={objects}
            selectedObjectIds={selectedObjectIds}
            selectedCellId={selectedCellId}
            tool={tool}
            transformerRef={transformerRef}
            selectedObject={selectedObject}
            isGroupedWithMask={isGroupedWithMask}
            maskObject={maskObject}
            canGroup={canGroup}
            canUngroup={canUngroup}
            onSelect={handleSelect}
            onUpdate={handleObjectUpdate}
            onCellClick={handleCellClick}
            onCellDblClick={handleCellDblClick}
            onGroup={handleGroupWithMask}
            onUngroup={handleUngroupFromMask}
          />
        </Stage>
      </div>
      {editingCell && (
        <CellEditor
          x={editingCell.x}
          y={editingCell.y}
          width={editingCell.width}
          height={editingCell.height}
          value={editingCell.value}
          onSave={handleCellEditorSave}
          onCancel={handleCellEditorCancel}
        />
      )}
      <ZoomControls />
    </div>
  );
};

export default EditorCanvas;
