import { useRef, useEffect, useCallback, useState } from "react";
import { Stage, Layer, Rect, Text, Group } from "react-konva";
import type { Stage as StageType } from "konva/lib/Stage";
import type { KonvaEventObject } from "konva/lib/Node";
import { useCanvasStore, useElements, useContainerSettings } from "@/stores/canvasStore";
import { ElementRenderer } from "./elements";
import { TransformableShape } from "./TransformableShape";
import { SnapGuides } from "./SnapGuides";
import { ContainerBounds } from "./ContainerBounds";
import { ContainerBackground } from "./ContainerBackground";

interface CanvasEditorProps {
  width?: number;
  height?: number;
}

export function CanvasEditor({ width = 800, height = 500 }: CanvasEditorProps) {
  const stageRef = useRef<StageType>(null);
  const containerRef = useRef<HTMLDivElement>(null);
  const [containerSize, setContainerSize] = useState({ width, height });

  const elements = useElements();

  // Use individual selectors for other values
  const selectedIds = useCanvasStore((state) => state.selectedIds);
  const zoom = useCanvasStore((state) => state.zoom);
  const clearSelection = useCanvasStore((state) => state.clearSelection);
  const setZoom = useCanvasStore((state) => state.setZoom);

  // Handle container resize
  useEffect(() => {
    const container = containerRef.current;
    if (!container) return;

    const resizeObserver = new ResizeObserver((entries) => {
      for (const entry of entries) {
        const { width: w, height: h } = entry.contentRect;
        setContainerSize({ width: w, height: h });
      }
    });

    resizeObserver.observe(container);
    return () => resizeObserver.disconnect();
  }, []);

  // Handle stage click (deselect)
  const handleStageClick = useCallback(
    (e: KonvaEventObject<MouseEvent>) => {
      // Only deselect if clicking on empty stage area
      if (e.target === e.target.getStage()) {
        clearSelection();
      }
    },
    [clearSelection]
  );

  // Handle wheel zoom with Ctrl key
  const handleWheel = useCallback(
    (e: KonvaEventObject<WheelEvent>) => {
      e.evt.preventDefault();

      // Only zoom with Ctrl key pressed
      if (!e.evt.ctrlKey) return;

      const scaleBy = 1.05;
      const newZoom = e.evt.deltaY > 0 ? zoom / scaleBy : zoom * scaleBy;

      // Clamp to limits (setZoom already clamps to 0.5-2)
      setZoom(newZoom);
    },
    [zoom, setZoom]
  );

  // Calculate actual canvas dimensions (scaled by zoom)
  const canvasWidth = containerSize.width / zoom;
  const canvasHeight = containerSize.height / zoom;

  // Get container settings for HTML mode check
  const containerSettings = useContainerSettings();
  const isHtmlMode = containerSettings.useCustomHtml;

  return (
    <div ref={containerRef} className="w-full h-full bg-white rounded-lg shadow-md overflow-hidden">
      <Stage
        ref={stageRef}
        width={containerSize.width}
        height={containerSize.height}
        scaleX={zoom}
        scaleY={zoom}
        onClick={handleStageClick}
        onTap={handleStageClick}
        onWheel={handleWheel}
      >
        {/* Background Layer */}
        <Layer listening={false}>
          {/* Plain white background */}
          <Rect x={0} y={0} width={canvasWidth} height={canvasHeight} fill="#ffffff" listening={false} />
          {/* Container Background (behind elements) */}
          <ContainerBackground containerSize={{ width: canvasWidth, height: canvasHeight }} />
        </Layer>

        {/* Elements Layer - dimmed when HTML mode is active */}
        <Layer opacity={isHtmlMode ? 0.15 : 1}>
          {elements.map((element) => (
            <ElementRenderer key={element.id} element={element} containerSize={{ width: canvasWidth, height: canvasHeight }} />
          ))}
        </Layer>

        {/* Transform Layer - hidden when HTML mode */}
        <Layer visible={!isHtmlMode}>
          <TransformableShape selectedIds={selectedIds} stageRef={stageRef} />
        </Layer>

        {/* Guides Layer */}
        <Layer listening={false}>
          <SnapGuides containerSize={{ width: canvasWidth, height: canvasHeight }} />
          <ContainerBounds containerSize={{ width: canvasWidth, height: canvasHeight }} />
        </Layer>

        {/* HTML Mode Overlay Layer - on top of everything */}
        {isHtmlMode && (
          <Layer listening={false}>
            <Group>
              {/* Semi-transparent grey overlay */}
              <Rect x={0} y={0} width={canvasWidth} height={canvasHeight} fill="#64748b" opacity={0.4} listening={false} />
              {/* Central indicator box */}
              <Rect
                x={canvasWidth / 2 - 220}
                y={canvasHeight / 2 - 100}
                width={440}
                height={200}
                fill="#0f172a"
                cornerRadius={16}
                shadowColor="#000000"
                shadowBlur={30}
                shadowOpacity={0.3}
                listening={false}
              />
              {/* Code icon background circle */}
              <Rect
                x={canvasWidth / 2 - 35}
                y={canvasHeight / 2 - 75}
                width={70}
                height={50}
                fill="#1e293b"
                cornerRadius={8}
                listening={false}
              />
              {/* Code icon */}
              <Text
                x={canvasWidth / 2 - 35}
                y={canvasHeight / 2 - 68}
                width={70}
                text="</>"
                fontSize={32}
                fontFamily="JetBrains Mono, Consolas, monospace"
                fontStyle="bold"
                fill="#3b82f6"
                align="center"
                listening={false}
              />
              {/* Title */}
              <Text
                x={canvasWidth / 2 - 200}
                y={canvasHeight / 2 - 8}
                width={400}
                text="Custom HTML Mode Active"
                fontSize={24}
                fontFamily="Inter, system-ui, -apple-system, sans-serif"
                fontStyle="bold"
                fill="#f8fafc"
                align="center"
                listening={false}
              />
              {/* Description */}
              <Text
                x={canvasWidth / 2 - 200}
                y={canvasHeight / 2 + 28}
                width={400}
                text="Canvas elements are greyed out."
                fontSize={14}
                fontFamily="Inter, system-ui, -apple-system, sans-serif"
                fill="#94a3b8"
                align="center"
                listening={false}
              />
              <Text
                x={canvasWidth / 2 - 200}
                y={canvasHeight / 2 + 50}
                width={400}
                text="The layout will use your custom HTML/CSS/JS instead."
                fontSize={14}
                fontFamily="Inter, system-ui, -apple-system, sans-serif"
                fill="#94a3b8"
                align="center"
                listening={false}
              />
              {/* Tip at bottom */}
              <Text
                x={canvasWidth / 2 - 200}
                y={canvasHeight / 2 + 78}
                width={400}
                text="Disable Custom HTML Mode in Container Settings to edit canvas"
                fontSize={11}
                fontFamily="Inter, system-ui, -apple-system, sans-serif"
                fill="#64748b"
                align="center"
                listening={false}
              />
            </Group>
          </Layer>
        )}
      </Stage>
    </div>
  );
}
