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

function TextField({
  element,
  isSelected,
  isSingleSelection,
  onSelect,
  onUpdate,
  onDelete,
  onDragStart,
  onDrag,
  charWidth,
  charHeight,
  toolMode
}) {
  const [isEditing, setIsEditing] = useState(false);
  const [editContent, setEditContent] = useState(element.content);
  const inputRef = useRef(null);

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

  const { handleClick } = useElementSelection({
    isSelected,
    onSelect,
    onDelete: () => {
      if (!isEditing) onDelete();
    },
    toolMode
  });

  useEffect(() => {
    if (isEditing && inputRef.current) {
      inputRef.current.focus();
      inputRef.current.select();
    }
  }, [isEditing]);

  const handleDoubleClick = (e) => {
    // Only allow editing in select mode
    if (toolMode === 'select') {
      e.stopPropagation();
      if (!isEditing) {
        setIsEditing(true);
        setEditContent(element.content);
      }
    }
  };

  const handleBlur = () => {
    if (isEditing) {
      setIsEditing(false);
      if (editContent !== element.content) {
        onUpdate({ content: editContent });
      }
    }
  };

  const handleKeyDown = (e) => {
    if (e.key === 'Enter') {
      e.preventDefault();
      handleBlur();
    } else if (e.key === 'Escape') {
      setIsEditing(false);
      setEditContent(element.content);
    }
  };

  const handleMouseDown = (e) => {
    if (isEditing) return;
    onSelect(); // Select element before dragging
    handleDragMouseDown(e, element.id);
  };

  useEffect(() => {
    if (!isSelected) {
      setIsEditing(false);
    }
  }, [isSelected]);

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

  // Display content directly (no binding resolution)
  const displayContent = element.content;

  // Use element class methods
  const multiLine = isTextMultiLine(element);
  const whiteSpace = getTextWhiteSpace(element);

  const style = {
    ...getElementStyle(element, charWidth, charHeight),
    minWidth: `${charWidth}px`,
    minHeight: `${charHeight}px`,
    whiteSpace
  };

  return (
    <div
      className={`text-field ${isSelected ? 'selected' : ''} ${isDragging ? 'dragging' : ''}`}
      style={style}
      onClick={handleClick}
      onDoubleClick={handleDoubleClick}
      onMouseDown={handleMouseDown}
    >
      {isEditing ? (
        <input
          ref={inputRef}
          type="text"
          className="text-field-input"
          value={editContent}
          onChange={(e) => setEditContent(e.target.value)}
          onBlur={handleBlur}
          onKeyDown={handleKeyDown}
          style={{ width: `${Math.max(editContent.length, 5) * charWidth}px` }}
        />
      ) : (
        <span
          className="text-field-content"
          style={{ whiteSpace }}
        >
          {displayContent}
        </span>
      )}
      {isSingleSelection && !isEditing && (
        <ResizeHandles
          element={element}
          onResize={handleResize}
          charWidth={charWidth}
          charHeight={charHeight}
        />
      )}
    </div>
  );
}

export default TextField;
