import { useState, useEffect } from 'react'
import { Trash2, Plus, ChevronDown, ChevronUp } from 'lucide-react'
import '../app.css'

const OPERATORS = [
  { value: 'gte', label: '≥ Größer gleich', types: ['integer', 'float'] },
  { value: 'lte', label: '≤ Kleiner gleich', types: ['integer', 'float'] },
  { value: 'gt', label: '> Größer', types: ['integer', 'float'] },
  { value: 'lt', label: '< Kleiner', types: ['integer', 'float'] },
  { value: 'eq', label: '= Gleich', types: ['integer', 'float', 'string'] },
  { value: 'neq', label: '≠ Ungleich', types: ['integer', 'float', 'string'] },
  { value: 'between', label: '⟷ Zwischen', types: ['integer', 'float'] },
]

const PASS_STRATEGIES = [
  { value: 'weighted_score', label: 'Gewichteter Score' },
  { value: 'all_must_pass', label: 'Alle müssen erfüllt sein' },
  { value: 'at_least_n', label: 'Mindestens N Regeln' },
]

export default function ProfileBuilder({ trainingType, onSave, onCancel, parameters }) {
  const [profile, setProfile] = useState(null)
  const [loading, setLoading] = useState(false)
  const [expandedSections, setExpandedSections] = useState({ minReq: true })
  const [successMessage, setSuccessMessage] = useState(null)

  useEffect(() => {
    // Initialize or load existing profile
    if (trainingType.profile) {
      setProfile(trainingType.profile)
    } else {
      // Create empty profile structure
      setProfile({
        version: '1.0',
        name: `${trainingType.name_de} (Profil)`,
        description: '',
        rule_sets: {
          minimum_requirements: {
            enabled: true,
            pass_strategy: 'weighted_score',
            pass_threshold: 0.6,
            rules: []
          },
          intensity_zones: {
            enabled: false,
            zones: []
          },
          training_effects: {
            enabled: false,
            default_effects: {
              primary_abilities: [],
              secondary_abilities: []
            }
          },
          periodization: {
            enabled: false,
            frequency: {
              per_week_optimal: 3,
              per_week_max: 5
            },
            recovery: {
              min_hours_between: 24
            }
          },
          performance_indicators: {
            enabled: false
          },
          safety: {
            enabled: false,
            warnings: []
          }
        }
      })
    }
  }, [trainingType])

  const toggleSection = (section) => {
    setExpandedSections(prev => ({ ...prev, [section]: !prev[section] }))
  }

  const updateRuleSet = (key, updates) => {
    setProfile(prev => ({
      ...prev,
      rule_sets: {
        ...prev.rule_sets,
        [key]: {
          ...prev.rule_sets[key],
          ...updates
        }
      }
    }))
  }

  const addRule = () => {
    const newRule = {
      parameter: parameters[0]?.key || 'duration_min',
      operator: 'gte',
      value: 0,
      weight: 3,
      optional: false,
      reason: ''
    }

    setProfile(prev => ({
      ...prev,
      rule_sets: {
        ...prev.rule_sets,
        minimum_requirements: {
          ...prev.rule_sets.minimum_requirements,
          rules: [...prev.rule_sets.minimum_requirements.rules, newRule]
        }
      }
    }))
  }

  const updateRule = (index, updates) => {
    setProfile(prev => {
      const rules = [...prev.rule_sets.minimum_requirements.rules]
      rules[index] = { ...rules[index], ...updates }
      return {
        ...prev,
        rule_sets: {
          ...prev.rule_sets,
          minimum_requirements: {
            ...prev.rule_sets.minimum_requirements,
            rules
          }
        }
      }
    })
  }

  const removeRule = (index) => {
    setProfile(prev => ({
      ...prev,
      rule_sets: {
        ...prev.rule_sets,
        minimum_requirements: {
          ...prev.rule_sets.minimum_requirements,
          rules: prev.rule_sets.minimum_requirements.rules.filter((_, i) => i !== index)
        }
      }
    }))
  }

  const handleSave = async () => {
    setLoading(true)
    try {
      await onSave(profile)
      setSuccessMessage('✓ Profil gespeichert!')
      setTimeout(() => {
        setSuccessMessage(null)
      }, 2000)
    } catch (err) {
      // Error is already handled by parent
    } finally {
      setLoading(false)
    }
  }

  if (!profile) return <div className="spinner" />

  const minReq = profile.rule_sets.minimum_requirements

  return (
    <div style={{ background: 'var(--surface)', borderRadius: '12px', padding: '20px' }}>
      <div style={{ marginBottom: '20px' }}>
        <h3 style={{ marginBottom: '8px' }}>
          {trainingType.icon} {trainingType.name_de} - Profil konfigurieren
        </h3>
        <p style={{ fontSize: '13px', color: 'var(--text2)' }}>
          Definiere Mindestanforderungen und Bewertungskriterien für diesen Trainingstyp
        </p>
      </div>

      {/* Success Message */}
      {successMessage && (
        <div style={{
          padding: '12px',
          background: 'var(--accent)',
          color: 'white',
          borderRadius: '8px',
          marginBottom: '16px',
          fontSize: '14px',
          fontWeight: '600'
        }}>
          {successMessage}
        </div>
      )}

      {/* Minimum Requirements */}
      <div className="card" style={{ marginBottom: '16px' }}>
        <div
          style={{
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'space-between',
            cursor: 'pointer'
          }}
          onClick={() => toggleSection('minReq')}
        >
          <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
            <h4 style={{ margin: 0 }}>Mindestanforderungen</h4>
            <label style={{ display: 'flex', alignItems: 'center', gap: '4px', fontSize: '13px' }}>
              <input
                type="checkbox"
                checked={minReq.enabled}
                onChange={(e) => {
                  e.stopPropagation()
                  updateRuleSet('minimum_requirements', { enabled: e.target.checked })
                }}
              />
              Aktiviert
            </label>
          </div>
          {expandedSections.minReq ? <ChevronUp size={18} /> : <ChevronDown size={18} />}
        </div>

        {expandedSections.minReq && minReq.enabled && (
          <div style={{ marginTop: '16px' }}>
            {/* Strategy */}
            <div style={{ marginBottom: '16px', paddingBottom: '16px', borderBottom: '1px solid var(--border)' }}>
              <div className="form-row" style={{ marginBottom: '8px' }}>
                <label className="form-label">Pass-Strategie</label>
                <select
                  className="form-select"
                  value={minReq.pass_strategy}
                  onChange={(e) => updateRuleSet('minimum_requirements', { pass_strategy: e.target.value })}
                >
                  {PASS_STRATEGIES.map(s => (
                    <option key={s.value} value={s.value}>{s.label}</option>
                  ))}
                </select>
              </div>

              {minReq.pass_strategy === 'weighted_score' && (
                <div className="form-row">
                  <label className="form-label">Threshold (Score 0-1)</label>
                  <input
                    type="number"
                    className="form-input"
                    step="0.1"
                    min="0"
                    max="1"
                    value={minReq.pass_threshold}
                    onChange={(e) => updateRuleSet('minimum_requirements', { pass_threshold: parseFloat(e.target.value) })}
                  />
                  <span className="form-unit">{(minReq.pass_threshold * 100).toFixed(0)}%</span>
                </div>
              )}
            </div>

            {/* Rules */}
            <div style={{ marginBottom: '16px' }}>
              <div style={{ fontWeight: '600', fontSize: '14px', marginBottom: '12px' }}>
                Regeln ({minReq.rules.length})
              </div>

              {minReq.rules.map((rule, idx) => {
                const param = parameters.find(p => p.key === rule.parameter)
                const availableOps = OPERATORS.filter(op =>
                  param ? op.types.includes(param.data_type) : true
                )
                const useWeights = minReq.pass_strategy === 'weighted_score'

                return (
                  <div
                    key={idx}
                    style={{
                      background: 'var(--surface2)',
                      padding: '12px',
                      borderRadius: '8px',
                      marginBottom: '8px'
                    }}
                  >
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: '12px' }}>
                      <div style={{ fontSize: '12px', fontWeight: '600', color: 'var(--text2)' }}>
                        Regel {idx + 1}
                      </div>
                      <button
                        className="btn"
                        onClick={() => removeRule(idx)}
                        style={{ padding: '4px 8px', minWidth: 'auto', fontSize: '11px' }}
                        title="Regel löschen"
                      >
                        <Trash2 size={12} /> Löschen
                      </button>
                    </div>

                    {/* Parameter */}
                    <div style={{ marginBottom: '8px' }}>
                      <label style={{ fontSize: '11px', color: 'var(--text3)', fontWeight: '600', display: 'block', marginBottom: '4px' }}>
                        WAS soll geprüft werden?
                      </label>
                      <select
                        className="form-select"
                        value={rule.parameter}
                        onChange={(e) => updateRule(idx, { parameter: e.target.value })}
                        style={{ fontSize: '13px', width: '100%' }}
                      >
                        {parameters.map(p => (
                          <option key={p.key} value={p.key}>
                            {p.name_de} ({p.unit || p.data_type})
                          </option>
                        ))}
                      </select>
                    </div>

                    {/* Operator + Value */}
                    <div style={{ marginBottom: '8px' }}>
                      <label style={{ fontSize: '11px', color: 'var(--text3)', fontWeight: '600', display: 'block', marginBottom: '4px' }}>
                        BEDINGUNG
                      </label>
                      <div style={{ display: 'flex', gap: '8px', alignItems: 'flex-start' }}>
                        <select
                          className="form-select"
                          value={rule.operator}
                          onChange={(e) => updateRule(idx, { operator: e.target.value })}
                          style={{ fontSize: '13px', flex: rule.operator === 'between' ? '0 0 80px' : '0 0 100px' }}
                        >
                          {availableOps.map(op => (
                            <option key={op.value} value={op.value}>{op.label}</option>
                          ))}
                        </select>

                        {rule.operator === 'between' ? (
                          <div style={{ flex: 1, display: 'flex', gap: '4px' }}>
                            <input
                              type="number"
                              className="form-input"
                              placeholder="Min"
                              value={Array.isArray(rule.value) ? rule.value[0] : 0}
                              onChange={(e) => updateRule(idx, {
                                value: [parseFloat(e.target.value) || 0, Array.isArray(rule.value) ? rule.value[1] : 0]
                              })}
                              style={{ fontSize: '13px', flex: 1 }}
                            />
                            <input
                              type="number"
                              className="form-input"
                              placeholder="Max"
                              value={Array.isArray(rule.value) ? rule.value[1] : 0}
                              onChange={(e) => updateRule(idx, {
                                value: [Array.isArray(rule.value) ? rule.value[0] : 0, parseFloat(e.target.value) || 0]
                              })}
                              style={{ fontSize: '13px', flex: 1 }}
                            />
                          </div>
                        ) : (
                          <input
                            type="number"
                            className="form-input"
                            placeholder="z.B. 90"
                            value={rule.value}
                            onChange={(e) => updateRule(idx, { value: parseFloat(e.target.value) || 0 })}
                            style={{ fontSize: '13px', flex: 1 }}
                          />
                        )}
                      </div>
                    </div>

                    {/* Weight - nur bei weighted_score */}
                    {useWeights && (
                      <div style={{ marginBottom: '8px', paddingTop: '8px', borderTop: '1px dashed var(--border)' }}>
                        <label style={{ fontSize: '11px', color: 'var(--text3)', fontWeight: '600', display: 'block', marginBottom: '4px' }}>
                          WICHTIGKEIT dieser Regel (1 = unwichtig, 10 = sehr wichtig)
                        </label>
                        <input
                          type="number"
                          className="form-input"
                          placeholder="1-10"
                          min="1"
                          max="10"
                          value={rule.weight}
                          onChange={(e) => updateRule(idx, { weight: parseInt(e.target.value) || 1 })}
                          style={{ fontSize: '13px', width: '80px' }}
                        />
                      </div>
                    )}

                    {/* Reason */}
                    <div style={{ marginBottom: '8px' }}>
                      <label style={{ fontSize: '11px', color: 'var(--text3)', fontWeight: '600', display: 'block', marginBottom: '4px' }}>
                        Begründung (optional)
                      </label>
                      <input
                        type="text"
                        className="form-input"
                        placeholder="z.B. 'Techniktraining sollte ruhig sein'"
                        value={rule.reason}
                        onChange={(e) => updateRule(idx, { reason: e.target.value })}
                        style={{ fontSize: '12px', width: '100%' }}
                      />
                    </div>

                    {/* Optional Checkbox */}
                    <label style={{ display: 'flex', alignItems: 'center', gap: '6px', fontSize: '12px', color: 'var(--text2)' }}>
                      <input
                        type="checkbox"
                        checked={rule.optional}
                        onChange={(e) => updateRule(idx, { optional: e.target.checked })}
                      />
                      Optional (Regel wird übersprungen wenn Parameter fehlt)
                    </label>
                  </div>
                )
              })}

              <button
                className="btn btn-secondary btn-full"
                onClick={addRule}
                style={{ marginTop: '8px' }}
              >
                <Plus size={14} /> Regel hinzufügen
              </button>
            </div>
          </div>
        )}
      </div>

      {/* Other Rule Sets - Future Features */}
      <div className="card" style={{ marginBottom: '16px', padding: '12px', background: 'var(--surface2)' }}>
        <div style={{ fontSize: '13px', color: 'var(--text2)' }}>
          <strong>Weitere Dimensionen</strong> (Analyse & Entwicklung, folgen später):
          <br />
          <span style={{ fontSize: '12px', lineHeight: '1.6', display: 'block', marginTop: '4px' }}>
            • <strong>Intensitätszonen:</strong> HF-Zonen-Verteilung analysieren<br />
            • <strong>Training Effects:</strong> Fähigkeitenentwicklung tracken<br />
            • <strong>Periodization:</strong> Frequenz & Recovery planen<br />
            • <strong>Performance:</strong> Fortschritt messen (Benchmarks, Trends)<br />
            • <strong>Safety:</strong> Warnungen bei Überbelastung
          </span>
        </div>
      </div>

      {/* Actions */}
      <div style={{ display: 'flex', gap: '12px', marginTop: '20px' }}>
        <button
          className="btn btn-primary"
          onClick={handleSave}
          disabled={loading}
          style={{ flex: 1 }}
        >
          💾 {loading ? 'Speichern...' : 'Profil speichern'}
        </button>
        <button
          className="btn btn-secondary"
          onClick={onCancel}
          style={{ flex: 1 }}
        >
          Abbrechen
        </button>
      </div>
    </div>
  )
}
