import React from 'react';
import { useReportData } from './DataContext';
import { getAvailableObjects, getAvailableFields } from './utils/dataResolver';
import { getAvailableArrays } from './utils/bandRenderer';
import ExpressionEditorPanel from './ExpressionEditorPanel';
import './ObjectInspector.css';

function ObjectInspector({ element, onUpdate, allElements = [] }) {
  const { reportData } = useReportData();

  if (!element) {
    return (
      <div className="object-inspector">
        <div className="inspector-header">Object Inspector</div>
        <div className="inspector-empty">No element selected</div>
      </div>
    );
  }

  const handleChange = (property, value) => {
    onUpdate({ [property]: value });
  };

  const handleNumberChange = (property, value) => {
    const numValue = parseInt(value, 10);
    if (!isNaN(numValue)) {
      onUpdate({ [property]: numValue });
    }
  };

  // Get available objects and fields for DBTextField
  // If DBTextField is inside a band, find the band and get fields from its data structure
  let availableObjects = [];
  let availableFields = [];
  let parentBand = null;

  if (element.type === 'dbtext') {
    // Check if this element is a child of a band
    parentBand = allElements.find(el => el.type === 'band' && el.children && el.children.includes(element.id));

    if (parentBand && parentBand.dataSource) {
      // Inside a band - get fields from band's data array structure
      let bandDataArray;

      if (parentBand.parentBandId) {
        // Nested band - resolve through parent chain
        const grandparentBand = allElements.find(el => el.id === parentBand.parentBandId);
        if (grandparentBand && grandparentBand.dataSource) {
          const grandparentData = reportData?.[grandparentBand.dataSource];
          if (Array.isArray(grandparentData) && grandparentData.length > 0) {
            // Navigate to nested array using parentBand.dataSource
            const nestedData = grandparentData[0][parentBand.dataSource];
            if (Array.isArray(nestedData) && nestedData.length > 0) {
              bandDataArray = nestedData;
            }
          }
        }
      } else {
        // Top-level band - get data directly
        bandDataArray = reportData?.[parentBand.dataSource];
      }

      if (Array.isArray(bandDataArray) && bandDataArray.length > 0) {
        // Get fields from first item in array
        availableFields = getAvailableFields(bandDataArray[0]);
      }
      // Don't show object dropdown when inside band
      availableObjects = [];
    } else {
      // Not inside a band - use normal object/field selection
      availableObjects = getAvailableObjects(reportData);
      availableFields = element.objectKey ? getAvailableFields(reportData[element.objectKey]) : [];
    }
  }

  // Get available arrays for Band data source
  // If this band has a parent, get arrays from parent's data structure
  let availableArrays = [];
  let currentBandParent = null;
  if (element.type === 'band') {
    if (element.parentBandId) {
      currentBandParent = allElements.find(el => el.id === element.parentBandId);
    }
    availableArrays = getAvailableArrays(reportData, currentBandParent);
  }

  // Get all bands for parent band dropdown (excluding current element)
  const availableBands = element.type === 'band'
    ? allElements.filter(el => el.type === 'band' && el.id !== element.id)
    : [];

  return (
    <div className="object-inspector">
      <div className="inspector-header">Object Inspector</div>

      <div className="inspector-section">
        <div className="section-title">General</div>

        <div className="property-row">
          <label>Type:</label>
          <input type="text" value={element.type} disabled />
        </div>

        <div className="property-row">
          <label>X:</label>
          <input
            type="number"
            value={element.x}
            onChange={(e) => handleNumberChange('x', e.target.value)}
          />
        </div>

        <div className="property-row">
          <label>Y:</label>
          <input
            type="number"
            value={element.y}
            onChange={(e) => handleNumberChange('y', e.target.value)}
          />
        </div>

        {(element.width !== undefined) && (
          <div className="property-row">
            <label>Width:</label>
            <input
              type="number"
              value={element.width}
              onChange={(e) => handleNumberChange('width', e.target.value)}
            />
          </div>
        )}

        {(element.height !== undefined) && (
          <div className="property-row">
            <label>Height:</label>
            <input
              type="number"
              value={element.height}
              onChange={(e) => handleNumberChange('height', e.target.value)}
            />
          </div>
        )}

        {element.length !== undefined && (
          <div className="property-row">
            <label>Length:</label>
            <input
              type="number"
              value={element.length}
              onChange={(e) => handleNumberChange('length', e.target.value)}
            />
          </div>
        )}
      </div>

      {/* TextField specific */}
      {element.type === 'text' && (
        <div className="inspector-section">
          <div className="section-title">Text</div>
          <div className="property-row">
            <label>Content:</label>
            <input
              type="text"
              value={element.content || ''}
              onChange={(e) => handleChange('content', e.target.value)}
            />
          </div>
        </div>
      )}

      {/* DBTextField specific */}
      {element.type === 'dbtext' && (
        <div className="inspector-section">
          <div className="section-title">Data Binding</div>

          {parentBand ? (
            <>
              <div className="property-info" style={{
                fontSize: '11px',
                color: '#667eea',
                marginBottom: '8px',
                padding: '6px',
                background: 'rgba(102, 126, 234, 0.1)',
                borderRadius: '3px'
              }}>
                {parentBand.parentBandId ? (
                  <>
                    Inside nested band: {parentBand.dataSource}
                    <br />
                    (within {allElements.find(el => el.id === parentBand.parentBandId)?.dataSource})
                  </>
                ) : (
                  <>Inside band: {parentBand.dataSource}</>
                )}
                <br />
                Fields auto-bind to current row
              </div>
              <div className="property-row">
                <label>Field:</label>
                <select
                  value={element.fieldPath || ''}
                  onChange={(e) => handleChange('fieldPath', e.target.value)}
                >
                  <option value="">-- Select Field --</option>
                  {availableFields.map(path => (
                    <option key={path} value={path}>{path}</option>
                  ))}
                </select>
              </div>
            </>
          ) : (
            <>
              <div className="property-row">
                <label>Object:</label>
                <select
                  value={element.objectKey || ''}
                  onChange={(e) => handleChange('objectKey', e.target.value)}
                >
                  <option value="">-- Select Object --</option>
                  {availableObjects.map(key => (
                    <option key={key} value={key}>{key}</option>
                  ))}
                </select>
              </div>

              <div className="property-row">
                <label>Field:</label>
                <select
                  value={element.fieldPath || ''}
                  onChange={(e) => handleChange('fieldPath', e.target.value)}
                  disabled={!element.objectKey}
                >
                  <option value="">-- Select Field --</option>
                  {availableFields.map(path => (
                    <option key={path} value={path}>{path}</option>
                  ))}
                </select>
              </div>
            </>
          )}

          <div className="property-row">
            <label>Data Type:</label>
            <select
              value={element.dataType || 'general'}
              onChange={(e) => handleChange('dataType', e.target.value)}
            >
              <option value="general">General</option>
              <option value="number">Number</option>
              <option value="date">Date</option>
              <option value="time">Time</option>
              <option value="datetime">Date &amp; Time</option>
            </select>
          </div>

          <div className="property-row">
            <label>Alignment:</label>
            <select
              value={element.alignment || 'left'}
              onChange={(e) => handleChange('alignment', e.target.value)}
            >
              <option value="left">Left</option>
              <option value="center">Center</option>
              <option value="right">Right</option>
            </select>
          </div>
        </div>
      )}

      {element.type === 'expr' && (
        <ExpressionEditorPanel element={element} onUpdate={onUpdate} reportData={reportData} allElements={allElements} />
      )}

      {/* Frame/Line specific */}
      {(element.type === 'frame' || element.type === 'hline' || element.type === 'vline') && (
        <div className="inspector-section">
          <div className="section-title">Style</div>
          <div className="property-row">
            <label>Style:</label>
            <select
              value={element.borderStyle || element.lineStyle || 'single'}
              onChange={(e) => {
                const prop = element.type === 'frame' ? 'borderStyle' : 'lineStyle';
                handleChange(prop, e.target.value);
              }}
            >
              <option value="single">Single</option>
              <option value="double">Double</option>
            </select>
          </div>
        </div>
      )}

      {/* Symbol specific */}
      {element.type === 'symbol' && (
        <div className="inspector-section">
          <div className="section-title">Symbol</div>
          <div className="property-row">
            <label>Character:</label>
            <input
              type="text"
              maxLength={1}
              value={element.char || ''}
              onChange={(e) => handleChange('char', e.target.value)}
            />
          </div>
        </div>
      )}

      {/* Band specific */}
      {element.type === 'band' && (
        <div className="inspector-section">
          <div className="section-title">Band</div>

          <div className="property-row">
            <label>Type:</label>
            <select
              value={element.bandType || 'detail'}
              onChange={(e) => handleChange('bandType', e.target.value)}
            >
              <option value="header">Header</option>
              <option value="detail">Detail</option>
              <option value="subdetail">Sub-Detail</option>
              <option value="footer">Footer</option>
              <option value="summary">Summary</option>
            </select>
          </div>

          <div className="property-row">
            <label>Data Source:</label>
            <select
              value={element.dataSource || ''}
              onChange={(e) => handleChange('dataSource', e.target.value)}
            >
              <option value="">-- No Data --</option>
              {availableArrays.map(arr => (
                <option key={arr.path} value={arr.path}>{arr.path}</option>
              ))}
            </select>
          </div>

          <div className="property-row">
            <label>Caption:</label>
            <input
              type="text"
              value={element.caption || ''}
              onChange={(e) => handleChange('caption', e.target.value)}
              placeholder="Auto-generated"
            />
          </div>

          <div className="property-row">
            <label>Parent Band:</label>
            <select
              value={element.parentBandId || ''}
              onChange={(e) => handleChange('parentBandId', e.target.value || null)}
            >
              <option value="">-- None (Root) --</option>
              {availableBands.map(band => (
                <option key={band.id} value={band.id}>
                  {band.caption || `${band.bandType}: ${band.dataSource}`}
                </option>
              ))}
            </select>
          </div>
        </div>
      )}
    </div>
  );
}

export default ObjectInspector;
