import React, { useState } from 'react';
import ResizeHandles from './ResizeHandles';
import { useElementDrag } from './hooks/useElementDrag';
import { useElementSelection } from './hooks/useElementSelection';
import { getElementStyle, isPositionOnFrameBorder } from './utils/elementUtils';
import './elements.css';

const BORDER_CHARS = {
  single: {
    topLeft: '┌',
    topRight: '┐',
    bottomLeft: '└',
    bottomRight: '┘',
    horizontal: '─',
    vertical: '│'
  },
  double: {
    topLeft: '╔',
    topRight: '╗',
    bottomLeft: '╚',
    bottomRight: '╝',
    horizontal: '═',
    vertical: '║'
  }
};

function FrameElement({ element, isSelected, isSingleSelection, onSelect, onDelete, onUpdate, onDragStart, onDrag, charWidth, charHeight, toolMode }) {
  const chars = BORDER_CHARS[element.borderStyle || 'single'];
  const [isHoveringBorder, setIsHoveringBorder] = useState(false);

  // Use custom hooks for drag and selection
  const { isDragging, handleMouseDown: handleDragMouseDown } = useElementDrag({
    isSelected,
    onDragStart,
    onDrag,
    toolMode
  });

  useElementSelection({
    isSelected,
    onSelect,
    onDelete,
    toolMode
  });

  const renderFrame = () => {
    const lines = [];
    const { width, height } = element;

    for (let row = 0; row < height; row++) {
      let line = '';
      for (let col = 0; col < width; col++) {
        if (row === 0 && col === 0) {
          line += chars.topLeft;
        } else if (row === 0 && col === width - 1) {
          line += chars.topRight;
        } else if (row === height - 1 && col === 0) {
          line += chars.bottomLeft;
        } else if (row === height - 1 && col === width - 1) {
          line += chars.bottomRight;
        } else if (row === 0 || row === height - 1) {
          line += chars.horizontal;
        } else if (col === 0 || col === width - 1) {
          line += chars.vertical;
        } else {
          line += ' ';
        }
      }
      lines.push(
        <div key={row} className="frame-line" style={{ height: `${charHeight}px` }}>
          {line}
        </div>
      );
    }
    return lines;
  };

  // Use element class method for style calculation
  const baseStyle = getElementStyle(element, charWidth, charHeight);
  const style = {
    ...baseStyle,
    cursor: (toolMode === 'select' && isHoveringBorder) ? 'pointer' : 'default'
  };

  // Check if a click position is on the border (not interior)
  const isClickOnBorder = (e) => {
    const rect = e.currentTarget.getBoundingClientRect();
    const relativeX = e.clientX - rect.left;
    const relativeY = e.clientY - rect.top;

    // Calculate which character cell was clicked
    const col = Math.floor(relativeX / charWidth);
    const row = Math.floor(relativeY / charHeight);

    // Use element class method to check if position is on border
    return isPositionOnFrameBorder(element, col, row);
  };

  const handleClick = (e) => {
    // Only handle selection in select mode and on border clicks
    if (toolMode === 'select' && isClickOnBorder(e)) {
      e.stopPropagation();
      onSelect(e);
    }
  };

  const handleMouseMove = (e) => {
    // Update hover state based on whether mouse is over border
    const onBorder = isClickOnBorder(e);
    if (onBorder !== isHoveringBorder) {
      setIsHoveringBorder(onBorder);
    }
  };

  const handleMouseDown = (e) => {
    // Only handle dragging in select mode and on border clicks
    if (toolMode !== 'select' || !isClickOnBorder(e)) return;

    onSelect(e); // Select element before dragging
    handleDragMouseDown(e, element.id);
  };

  const handleResize = (updates) => {
    onUpdate(updates);
  };

  return (
    <div
      className={`frame-element ${isSelected ? 'selected' : ''} ${isDragging ? 'dragging' : ''}`}
      style={style}
      onClick={handleClick}
      onMouseDown={handleMouseDown}
      onMouseMove={handleMouseMove}
      onMouseLeave={() => setIsHoveringBorder(false)}
    >
      {renderFrame()}
      {isSingleSelection && (
        <ResizeHandles
          element={element}
          onResize={handleResize}
          charWidth={charWidth}
          charHeight={charHeight}
        />
      )}
    </div>
  );
}

export default FrameElement;
