import { useState, useEffect } from 'react'

/**
 * QuestionAugmentationPanel - Fragenergänzungs-Konfiguration
 *
 * Props:
 * - node: React Flow Node object (type='analysis')
 * - onChange: (nodeId, updates) => void
 */
export function QuestionAugmentationPanel({ node, onChange }) {
  const [questions, setQuestions] = useState(node.data.questions || [])

  // Sync to parent when questions change
  useEffect(() => {
    onChange(node.id, { questions })
  }, [questions])

  const handleAddQuestion = () => {
    const newQuestion = {
      id: `q${Date.now()}`,
      type: 'relevanz',
      question: '',
      answer_spectrum: []
    }
    setQuestions([...questions, newQuestion])
  }

  const handleRemoveQuestion = (index) => {
    setQuestions(questions.filter((_, i) => i !== index))
  }

  const handleQuestionChange = (index, field, value) => {
    const updated = [...questions]
    updated[index] = { ...updated[index], [field]: value }
    setQuestions(updated)
  }

  return (
    <div className="config-section">
      <h3>Fragenergänzung</h3>

      {questions.length === 0 && (
        <div className="help-text" style={{ marginBottom: '12px' }}>
          Keine Fragen definiert. Fügen Sie Fragen hinzu, um Signale für Logik-Knoten zu erzeugen.
        </div>
      )}

      {questions.map((q, idx) => (
        <QuestionEditor
          key={idx}
          question={q}
          index={idx}
          onChange={(field, value) => handleQuestionChange(idx, field, value)}
          onRemove={() => handleRemoveQuestion(idx)}
        />
      ))}

      <button className="btn-secondary btn-full" onClick={handleAddQuestion}>
        + Frage hinzufügen
      </button>
    </div>
  )
}

/**
 * QuestionEditor - Einzelne Frage editieren
 */
function QuestionEditor({ question, index, onChange, onRemove }) {
  const [spectrumInput, setSpectrumInput] = useState('')

  const handleAddAnswer = () => {
    if (!spectrumInput.trim()) return

    const newSpectrum = [...(question.answer_spectrum || []), spectrumInput.trim()]
    onChange('answer_spectrum', newSpectrum)
    setSpectrumInput('')
  }

  const handleRemoveAnswer = (answer) => {
    const newSpectrum = question.answer_spectrum.filter(a => a !== answer)
    onChange('answer_spectrum', newSpectrum)
  }

  const handleKeyPress = (e) => {
    if (e.key === 'Enter') {
      e.preventDefault()
      handleAddAnswer()
    }
  }

  return (
    <div className="question-editor">
      <div className="question-header">
        <span>Frage {index + 1}</span>
        <button className="btn-icon" onClick={onRemove} title="Frage löschen">
          🗑️
        </button>
      </div>

      <label>Frage-ID</label>
      <input
        type="text"
        value={question.id || ''}
        onChange={(e) => onChange('id', e.target.value)}
        placeholder="z.B. relevanz"
      />

      <label>Fragetyp</label>
      <select
        value={question.type || 'relevanz'}
        onChange={(e) => onChange('type', e.target.value)}
      >
        <option value="relevanz">Relevanz</option>
        <option value="prioritaet">Priorität</option>
        <option value="selektion">Selektion</option>
        <option value="ausschluss">Ausschluss</option>
        <option value="eskalation">Eskalation</option>
        <option value="unsicherheit">Unsicherheit</option>
      </select>

      <label>Fragetext</label>
      <textarea
        value={question.question || ''}
        onChange={(e) => onChange('question', e.target.value)}
        placeholder="z.B. Ist diese Analyse relevant für den Nutzer?"
        rows={3}
      />

      <label>Antwortmöglichkeiten (mind. 2)</label>
      <div className="tag-input-container">
        <div className="tags">
          {(question.answer_spectrum || []).map((answer, i) => (
            <span key={i} className="tag">
              {answer}
              <button
                onClick={() => handleRemoveAnswer(answer)}
                className="tag-remove"
                title="Entfernen"
              >
                ×
              </button>
            </span>
          ))}
        </div>

        <div style={{ display: 'flex', gap: '8px', marginTop: '8px' }}>
          <input
            type="text"
            value={spectrumInput}
            onChange={(e) => setSpectrumInput(e.target.value)}
            onKeyPress={handleKeyPress}
            placeholder="z.B. ja, nein, unklar"
            style={{ flex: 1 }}
          />
          <button className="btn-secondary" onClick={handleAddAnswer}>
            +
          </button>
        </div>
      </div>

      {question.answer_spectrum && question.answer_spectrum.length < 2 && (
        <div className="help-text" style={{ color: 'var(--danger)' }}>
          ⚠️ Mindestens 2 Antworten erforderlich
        </div>
      )}
    </div>
  )
}

// Zusätzliches CSS für Tags (inline styles)
const tagStyles = `
.tag-input-container {
  margin-bottom: 8px;
}

.tags {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
  margin-bottom: 8px;
}

.tag {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  padding: 4px 8px;
  background: var(--accent);
  color: white;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.tag-remove {
  background: none;
  border: none;
  color: white;
  cursor: pointer;
  font-size: 16px;
  line-height: 1;
  padding: 0;
  margin-left: 2px;
  opacity: 0.8;
}

.tag-remove:hover {
  opacity: 1;
}
`

// Inject styles (nur einmal)
if (typeof document !== 'undefined' && !document.getElementById('question-panel-styles')) {
  const styleEl = document.createElement('style')
  styleEl.id = 'question-panel-styles'
  styleEl.textContent = tagStyles
  document.head.appendChild(styleEl)
}
