/**
 * Container Bounds Visualization
 *
 * Shows the calculated oppb-price-container bounds in the canvas editor.
 * This helps users understand how absolute positioning will work on the frontend.
 *
 * The container label is now interactive:
 * - Hover shows a settings gear icon
 * - Click opens the container settings panel
 *
 * NOTE: Container background/border rendering is now handled by ContainerBackground.tsx
 * This component only shows overlay indicators (padding/margin guides, labels).
 */

import {Rect, Line, Text, Group, Circle} from "react-konva";
import {useMemo, useState, useCallback} from "react";
import {
  useCanvasStore,
  useElements,
  useContainerSelected,
  useContainerSettings,
} from "@/stores/canvasStore";
import {calculateContainerBounds} from "@/utils/layoutAnalyzer";

interface ContainerBoundsProps {
  containerSize: {width: number; height: number};
}

export function ContainerBounds({
  containerSize: _containerSize,
}: ContainerBoundsProps) {
  const elements = useElements();
  const showContainerBounds = useCanvasStore(
    (state) => state.showContainerBounds
  );
  const selectContainer = useCanvasStore((state) => state.selectContainer);
  const containerSelected = useContainerSelected();
  const containerSettings = useContainerSettings();

  const [isLabelHovered, setIsLabelHovered] = useState(false);

  // Calculate bounds from visible elements
  const bounds = useMemo(() => {
    const visibleElements = elements.filter((el) => el.visible);
    if (visibleElements.length === 0) return null;

    return calculateContainerBounds(visibleElements, 8); // 8px padding
  }, [elements]);

  // Handle label click - select container
  const handleLabelClick = useCallback(() => {
    selectContainer();
  }, [selectContainer]);

  // Handle label hover
  const handleLabelMouseEnter = useCallback(() => {
    setIsLabelHovered(true);
  }, []);

  const handleLabelMouseLeave = useCallback(() => {
    setIsLabelHovered(false);
  }, []);

  if (!showContainerBounds || !bounds) {
    return null;
  }

  // Check if any element uses absolute positioning
  const hasAbsoluteElements = elements.some(
    (el) => el.visible && el.positionType === "absolute"
  );

  // Colors based on state
  const baseColor = hasAbsoluteElements ? "#8b5cf6" : "#94a3b8";
  const hoverColor = "#3b82f6";
  const selectedColor = "#2563eb";
  const labelColor = containerSelected
    ? selectedColor
    : isLabelHovered
    ? hoverColor
    : baseColor;

  // Extract container settings for indicator overlays
  const {padding, margin} = containerSettings;

  // Safe accessors for padding (default to 0)
  const padTop = padding?.top?.desktop ?? 0;
  const padRight = padding?.right?.desktop ?? 0;
  const padBottom = padding?.bottom?.desktop ?? 0;
  const padLeft = padding?.left?.desktop ?? 0;

  // Safe accessors for margin (default to 0)
  const marginTop = margin?.top?.desktop ?? 0;
  const marginRight = margin?.right?.desktop ?? 0;
  const marginBottom = margin?.bottom?.desktop ?? 0;
  const marginLeft = margin?.left?.desktop ?? 0;

  // Calculate expanded bounds with padding
  const paddedBounds = {
    x: bounds.x - padLeft,
    y: bounds.y - padTop,
    width: bounds.width + padLeft + padRight,
    height: bounds.height + padTop + padBottom,
  };

  // Calculate outer bounds with margin
  const marginBounds = {
    x: paddedBounds.x - marginLeft,
    y: paddedBounds.y - marginTop,
    width: paddedBounds.width + marginLeft + marginRight,
    height: paddedBounds.height + marginTop + marginBottom,
  };

  // Check if there are padding/margin to show indicators
  const hasPadding = padTop > 0 || padRight > 0 || padBottom > 0 || padLeft > 0;
  const hasMargin =
    marginTop > 0 || marginRight > 0 || marginBottom > 0 || marginLeft > 0;

  return (
    <Group>
      {/* Margin indicator (outermost, faded) */}
      {hasMargin && (
        <Rect
          x={marginBounds.x}
          y={marginBounds.y}
          width={marginBounds.width}
          height={marginBounds.height}
          stroke="#f59e0b"
          strokeWidth={1}
          dash={[4, 4]}
          fill="rgba(245, 158, 11, 0.05)"
          listening={false}
        />
      )}

      {/* Padding indicator (between content and border) */}
      {hasPadding && (
        <Rect
          x={paddedBounds.x}
          y={paddedBounds.y}
          width={paddedBounds.width}
          height={paddedBounds.height}
          stroke="#10b981"
          strokeWidth={1}
          dash={[2, 2]}
          fill="transparent"
          listening={false}
        />
      )}

      {/* Content boundary rectangle (original bounds without padding/margin) */}
      <Rect
        x={bounds.x}
        y={bounds.y}
        width={bounds.width}
        height={bounds.height}
        stroke={containerSelected ? selectedColor : baseColor}
        strokeWidth={containerSelected ? 2 : 1}
        dash={containerSelected ? undefined : [6, 4]}
        fill="transparent"
        listening={false}
      />

      {/* Corner markers */}
      {[
        {x: bounds.x, y: bounds.y}, // top-left
        {x: bounds.x + bounds.width, y: bounds.y}, // top-right
        {x: bounds.x, y: bounds.y + bounds.height}, // bottom-left
        {x: bounds.x + bounds.width, y: bounds.y + bounds.height}, // bottom-right
      ].map((corner, i) => (
        <Group key={i} x={corner.x} y={corner.y}>
          {/* Horizontal line */}
          <Line
            points={[i % 2 === 0 ? 0 : -8, 0, i % 2 === 0 ? 8 : 0, 0]}
            stroke={containerSelected ? selectedColor : baseColor}
            strokeWidth={1}
            listening={false}
          />
          {/* Vertical line */}
          <Line
            points={[0, i < 2 ? 0 : -8, 0, i < 2 ? 8 : 0]}
            stroke={containerSelected ? selectedColor : baseColor}
            strokeWidth={1}
            listening={false}
          />
        </Group>
      ))}

      {/* Interactive Container Label with Settings Icon */}
      <Group
        x={bounds.x}
        y={bounds.y - 18}
        onMouseEnter={handleLabelMouseEnter}
        onMouseLeave={handleLabelMouseLeave}
        onClick={handleLabelClick}
        onTap={handleLabelClick}
      >
        {/* Label background for better click area */}
        <Rect
          x={-4}
          y={-2}
          width={isLabelHovered || containerSelected ? 140 : 115}
          height={14}
          fill={
            isLabelHovered || containerSelected
              ? "rgba(37, 99, 235, 0.1)"
              : "transparent"
          }
          cornerRadius={3}
          listening={true}
        />

        {/* Container label text */}
        <Text
          x={0}
          y={0}
          text="oppb-price-container"
          fontSize={10}
          fontFamily="monospace"
          fill={labelColor}
          fontStyle={containerSelected ? "bold" : "normal"}
          listening={false}
        />

        {/* Settings gear icon (shown on hover or when selected) */}
        {(isLabelHovered || containerSelected) && (
          <Group x={105} y={5}>
            {/* Gear outer circle */}
            <Circle radius={5} fill={labelColor} listening={false} />
            {/* Gear inner circle (hole) */}
            <Circle
              radius={2}
              fill={
                isLabelHovered || containerSelected
                  ? "rgba(37, 99, 235, 0.1)"
                  : "#f8fafc"
              }
              listening={false}
            />
            {/* Gear teeth (simplified as lines) */}
            {[0, 60, 120, 180, 240, 300].map((angle) => {
              const rad = (angle * Math.PI) / 180;
              const x1 = Math.cos(rad) * 3.5;
              const y1 = Math.sin(rad) * 3.5;
              const x2 = Math.cos(rad) * 6;
              const y2 = Math.sin(rad) * 6;
              return (
                <Line
                  key={angle}
                  points={[x1, y1, x2, y2]}
                  stroke={
                    isLabelHovered || containerSelected
                      ? "rgba(37, 99, 235, 0.1)"
                      : "#f8fafc"
                  }
                  strokeWidth={2}
                  lineCap="round"
                  listening={false}
                />
              );
            })}
          </Group>
        )}
      </Group>

      {/* Dimensions label */}
      <Text
        x={bounds.x + bounds.width + 4}
        y={bounds.y + bounds.height / 2 - 6}
        text={`${Math.round(bounds.width)}×${Math.round(bounds.height)}`}
        fontSize={9}
        fontFamily="monospace"
        fill={containerSelected ? selectedColor : baseColor}
        listening={false}
      />

      {/* Origin marker for absolute positioning */}
      {hasAbsoluteElements && (
        <Group x={bounds.x} y={bounds.y}>
          {/* Origin crosshair */}
          <Line
            points={[-4, 0, 4, 0]}
            stroke="#8b5cf6"
            strokeWidth={2}
            listening={false}
          />
          <Line
            points={[0, -4, 0, 4]}
            stroke="#8b5cf6"
            strokeWidth={2}
            listening={false}
          />
          {/* Origin label */}
          <Text
            x={6}
            y={2}
            text="(0,0)"
            fontSize={8}
            fontFamily="monospace"
            fill="#8b5cf6"
            listening={false}
          />
        </Group>
      )}

      {/* Show relative position for absolute elements */}
      {elements
        .filter((el) => el.visible && el.positionType === "absolute")
        .map((el) => {
          const relX = Math.round(el.position.x - bounds.x);
          const relY = Math.round(el.position.y - bounds.y);

          return (
            <Group key={el.id}>
              {/* Position indicator line from origin to element */}
              <Line
                points={[bounds.x, bounds.y, el.position.x, el.position.y]}
                stroke="#8b5cf6"
                strokeWidth={0.5}
                dash={[2, 2]}
                opacity={0.5}
                listening={false}
              />
              {/* Position label */}
              <Text
                x={el.position.x + el.size.width + 4}
                y={el.position.y}
                text={`(${relX}, ${relY})`}
                fontSize={9}
                fontFamily="monospace"
                fill="#8b5cf6"
                listening={false}
              />
            </Group>
          );
        })}
    </Group>
  );
}
