import React from 'react';
import { useReportData } from './DataContext';
import { useBandContext } from './BandContext';
import { resolveDBTextValue } from './utils/dataResolver';
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 formatValue(raw, dataType) {
  if (raw === '' || raw === null || raw === undefined) return '';
  switch (dataType) {
    case 'number': {
      const n = Number(raw);
      return isNaN(n) ? '' : String(n);
    }
    case 'date': {
      const d = new Date(raw);
      return isNaN(d.getTime()) ? '' : d.toLocaleDateString();
    }
    case 'time': {
      const d = new Date(raw);
      return isNaN(d.getTime()) ? '' : d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
    }
    case 'datetime': {
      const d = new Date(raw);
      return isNaN(d.getTime()) ? '' : d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
    }
    default:
      return String(raw);
  }
}

function DBTextField({
  element,
  isSelected,
  isSingleSelection,
  onSelect,
  onUpdate,
  onDelete,
  onDragStart,
  onDrag,
  charWidth,
  charHeight,
  previewMode = false,
  toolMode,
  parentBandId = null // ID of parent band (for automatic data binding)
}) {
  const { reportData } = useReportData();
  const { currentBandData } = useBandContext();

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

  const { handleClick } = useElementSelection({
    isSelected,
    onSelect,
    onDelete,
    toolMode
  });

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

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

  // Resolve data value
  const rawValue = previewMode
    ? resolveDBTextValue(reportData, element.objectKey, element.fieldPath, parentBandId, { currentBandData })
    : parentBandId
      ? `{${element.fieldPath}}` // Inside band: show field only
      : `{${element.objectKey}.${element.fieldPath}}`; // Outside band: show object.field

  const displayContent = previewMode
    ? formatValue(rawValue, element.dataType || 'general')
    : rawValue;

  // Check if data is resolved
  // If inside a band, only fieldPath is required; otherwise both objectKey and fieldPath are required
  const isUnresolved = parentBandId
    ? (!element.fieldPath || (previewMode && !displayContent))
    : (!element.objectKey || !element.fieldPath || (previewMode && !displayContent));

  // 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,
    textAlign: element.alignment || 'left',
  };

  return (
    <div
      className={`db-text-field ${isSelected ? 'selected' : ''} ${isDragging ? 'dragging' : ''} ${isUnresolved ? 'unresolved' : ''}`}
      style={style}
      onClick={handleClick}
      onMouseDown={handleMouseDown}
    >
      <span className="db-text-field-content" style={{ whiteSpace }}>
        {displayContent || '(No Data)'}
      </span>
      {isSingleSelection && (
        <ResizeHandles
          element={element}
          onResize={handleResize}
          charWidth={charWidth}
          charHeight={charHeight}
        />
      )}
    </div>
  );
}

export default DBTextField;
