import React, { useState, useRef } from 'react';
import { getAvailableFields, getAvailableObjects } from './utils/dataResolver';

function ExpressionEditorPanel({ element, onUpdate, reportData, allElements }) {
  const [selectedField, setSelectedField] = useState('');
  const textareaRef = useRef(null);

  const parentBand = allElements.find(el => el.type === 'band' && el.children && el.children.includes(element.id));

  let availableFields = [];

  if (parentBand && parentBand.dataSource) {
    let bandDataArray;

    if (parentBand.parentBandId) {
      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) {
          const nestedData = grandparentData[0][parentBand.dataSource];
          if (Array.isArray(nestedData) && nestedData.length > 0) {
            bandDataArray = nestedData;
          }
        }
      }
    } else {
      bandDataArray = reportData?.[parentBand.dataSource];
    }

    if (Array.isArray(bandDataArray) && bandDataArray.length > 0) {
      availableFields = getAvailableFields(bandDataArray[0]);
    }
  } else {
    const objectKeys = getAvailableObjects(reportData);
    objectKeys.forEach(objectKey => {
      const fields = getAvailableFields(reportData[objectKey]);
      fields.forEach(f => availableFields.push(`${objectKey}.${f}`));
    });
  }

  const insertAtCursor = (text) => {
    const ta = textareaRef.current;
    if (!ta) { onUpdate({ expression: (element.expression || '') + text }); return; }
    const start = ta.selectionStart;
    const end = ta.selectionEnd;
    const current = element.expression || '';
    const next = current.slice(0, start) + text + current.slice(end);
    onUpdate({ expression: next });
    requestAnimationFrame(() => {
      ta.selectionStart = ta.selectionEnd = start + text.length;
      ta.focus();
    });
  };

  return (
    <div className="inspector-section">
      <div className="section-title">Expression</div>

      <textarea
        ref={textareaRef}
        value={element.expression || ''}
        onChange={(e) => onUpdate({ expression: e.target.value })}
        rows={3}
        style={{ width: '100%', fontFamily: 'monospace', fontSize: '11px', resize: 'vertical', boxSizing: 'border-box' }}
      />

      <select value={selectedField} onChange={e => setSelectedField(e.target.value)} style={{ width: '100%', marginBottom: '3px', boxSizing: 'border-box' }}>
        <option value="">-- field --</option>
        {availableFields.map(f => <option key={f} value={f}>{f}</option>)}
      </select>
      <div className="expr-btn-row">
        <button onClick={() => { if (selectedField) insertAtCursor(`[${selectedField}]`); }}>Insert Field</button>
      </div>

      <div className="expr-btn-row">
        {['+', '-', '*', '/'].map(op => <button key={op} onClick={() => insertAtCursor(` ${op} `)}>{op}</button>)}
        <button onClick={() => insertAtCursor('(')}>(</button>
        <button onClick={() => insertAtCursor(')')}>)</button>
      </div>

      <div className="expr-btn-row">
        <button onClick={() => insertAtCursor('IF( , , )')}>IF( , , )</button>
      </div>

      <div className="expr-btn-row">
        {['=', '!=', '>', '<', '>=', '<='].map(op => <button key={op} onClick={() => insertAtCursor(` ${op} `)}>{op}</button>)}
      </div>

      <div className="expr-btn-row">
        <button onClick={() => onUpdate({ expression: '' })}>Clear</button>
      </div>

      <div className="property-row">
        <label>Data Type:</label>
        <select value={element.dataType || 'general'} onChange={e => onUpdate({ 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 => onUpdate({ alignment: e.target.value })}>
          <option value="left">Left</option>
          <option value="center">Center</option>
          <option value="right">Right</option>
        </select>
      </div>
    </div>
  );
}

export default ExpressionEditorPanel;
