import { useState } from 'react'
import { api } from '../../../utils/api'

/**
 * WorkflowExecutePanel - Execution Controls für Workflow Editor
 *
 * Features:
 * - Execute Button mit Loading State
 * - Error Handling
 * - Success State
 * - Debug Mode Toggle
 *
 * Part 2: Frontend Execute Integration
 */
export function WorkflowExecutePanel({
  currentPrompt,
  onExecutionComplete,
  disabled = false
}) {
  const [executing, setExecuting] = useState(false)
  const [error, setError] = useState(null)
  const [debugMode, setDebugMode] = useState(true)

  const handleExecute = async () => {
    if (!currentPrompt || !currentPrompt.slug) {
      setError('Workflow muss zuerst gespeichert werden (benötigt slug)')
      return
    }

    try {
      setExecuting(true)
      setError(null)

      console.log('🚀 Executing workflow:', currentPrompt.slug)

      const result = await api.executeWorkflow(
        currentPrompt.slug,
        null,  // variables (später erweiterbar)
        debugMode,
        false  // save (nicht in ai_insights speichern)
      )

      console.log('✅ Workflow execution completed:', result)

      // Success - kurze Bestätigung
      if (result.status === 'completed') {
        // Callback mit result
        if (onExecutionComplete) {
          onExecutionComplete(result)
        }
      } else if (result.status === 'failed') {
        setError(result.error || 'Workflow-Ausführung fehlgeschlagen')
      }

    } catch (e) {
      console.error('❌ Workflow execution error:', e)
      setError(e.message)
    } finally {
      setExecuting(false)
    }
  }

  return (
    <div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
      {/* Debug Mode Toggle */}
      <label
        style={{
          display: 'flex',
          alignItems: 'center',
          gap: '4px',
          fontSize: '12px',
          color: 'var(--text2)',
          cursor: 'pointer'
        }}
        title="Debug-Modus zeigt detaillierte Node-States im Ergebnis"
      >
        <input
          type="checkbox"
          checked={debugMode}
          onChange={(e) => setDebugMode(e.target.checked)}
          disabled={executing}
        />
        Debug
      </label>

      {/* Execute Button */}
      <button
        className="btn-primary"
        onClick={handleExecute}
        disabled={disabled || executing || !currentPrompt}
        title={
          !currentPrompt
            ? 'Workflow muss zuerst gespeichert werden'
            : disabled
            ? 'Workflow hat Validierungsfehler'
            : 'Workflow ausführen'
        }
        style={{
          minWidth: '120px',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          gap: '8px'
        }}
      >
        {executing ? (
          <>
            <span className="spinner" style={{ width: 14, height: 14 }} />
            Executing...
          </>
        ) : (
          <>
            ▶️ Execute
          </>
        )}
      </button>

      {/* Error Display */}
      {error && (
        <div
          style={{
            padding: '6px 12px',
            background: 'var(--danger)',
            color: 'white',
            borderRadius: '4px',
            fontSize: '12px',
            maxWidth: '300px',
            overflow: 'hidden',
            textOverflow: 'ellipsis',
            whiteSpace: 'nowrap'
          }}
          title={error}
        >
          ❌ {error}
        </div>
      )}
    </div>
  )
}
