import { useState, useEffect } from 'react'
import Icon from './components/Icon'
import ContextMenu from './components/ContextMenu'
import {
  onMessage, notifyReady,
  setOverridesEnabled, addRule, updateRule, deleteRule,
  reorderRules, duplicateRule, reapplyOverrides, clearOverrideRules,
  savePreset, loadPreset, deletePreset,
  saveRuleTemplate, addFromTemplate, deleteRuleTemplate,
} from './lib/rhinoBridge'

const COND_TYPES = [
  { value: 'layer_name',  label: 'Layer-Name' },
  { value: 'user_string', label: 'UserString' },
  { value: 'object_name', label: 'Objekt-Name' },
]

const OPS = [
  { value: 'equals',      label: '=' },
  { value: 'not_equals',  label: '≠' },
  { value: 'contains',    label: 'enthält' },
  { value: 'starts_with', label: 'beginnt mit' },
  { value: 'ends_with',   label: 'endet mit' },
]

const labelXs = {
  fontSize: 9, color: 'var(--text-muted)',
  textTransform: 'uppercase', letterSpacing: '0.06em',
  fontWeight: 600,
}

// ---------------------------------------------------------------------------

function ConditionLeaf({ cond, layers, onChange, onRemove, canRemove }) {
  const t = cond?.type || 'layer_name'
  const op = cond?.operator || 'equals'
  return (
    <div style={{
      display: 'flex', flexDirection: 'column', gap: 6,
      padding: 8,
      border: '1px solid var(--border-light)', borderRadius: 'var(--r-lg)',
      background: 'var(--bg-section)',
    }}>
      <div style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
        <select
          value={t}
          onChange={(e) => onChange({ ...cond, type: e.target.value })}
          style={{ flex: 1, minWidth: 0 }}
        >
          {COND_TYPES.map(c => <option key={c.value} value={c.value}>{c.label}</option>)}
        </select>
        {canRemove && (
          <button onClick={onRemove} className="btn-icon-danger"
                  title="Diese Bedingung entfernen">
            <Icon name="close" size={14} />
          </button>
        )}
      </div>
      {t === 'user_string' && (
        <input
          type="text" placeholder="Key"
          value={cond?.key || ''}
          onChange={(e) => onChange({ ...cond, key: e.target.value })}
          style={{ width: '100%' }}
        />
      )}
      <div style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
        <select
          value={op}
          onChange={(e) => onChange({ ...cond, operator: e.target.value })}
          style={{ flexShrink: 0 }}
        >
          {OPS.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
        </select>
        {t === 'layer_name' ? (
          <select
            value={cond?.value || ''}
            onChange={(e) => onChange({ ...cond, value: e.target.value })}
            style={{ flex: 1, minWidth: 0 }}
          >
            <option value="">—</option>
            {(layers || []).map(l => (
              <option key={l.fullPath} value={l.fullPath}>{l.fullPath}</option>
            ))}
          </select>
        ) : (
          <input
            type="text" placeholder="Wert"
            value={cond?.value || ''}
            onChange={(e) => onChange({ ...cond, value: e.target.value })}
            style={{ flex: 1, minWidth: 0 }}
          />
        )}
      </div>
    </div>
  )
}

function ConditionsEditor({ rule, layers, onChange }) {
  const conds = rule.conditions && rule.conditions.length > 0
    ? rule.conditions
    : (rule.condition ? [rule.condition] : [{ type: 'layer_name', operator: 'equals', value: '' }])
  const logic = (rule.conditionsLogic || 'and').toLowerCase()

  const update = (i, newCond) => {
    const next = conds.slice()
    next[i] = newCond
    onChange({ ...rule, conditions: next, condition: undefined })
  }
  const remove = (i) => {
    const next = conds.slice()
    next.splice(i, 1)
    onChange({ ...rule, conditions: next.length ? next : [{ type: 'layer_name', operator: 'equals', value: '' }], condition: undefined })
  }
  const add = () => {
    const next = conds.slice()
    next.push({ type: 'layer_name', operator: 'equals', value: '' })
    onChange({ ...rule, conditions: next, condition: undefined })
  }
  const setLogic = (l) => onChange({ ...rule, conditionsLogic: l })

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
      {conds.length > 1 && (
        <div style={{ display: 'flex', gap: 4, alignItems: 'center' }}>
          <span style={{ fontSize: 10, color: 'var(--text-muted)' }}>Logik:</span>
          <button
            onClick={() => setLogic('and')}
            className={logic === 'and' ? 'btn-contained' : 'btn-outlined'}
            title="Alle Bedingungen müssen zutreffen"
          >AND</button>
          <button
            onClick={() => setLogic('or')}
            className={logic === 'or' ? 'btn-contained' : 'btn-outlined'}
            title="Mindestens eine Bedingung muss zutreffen"
          >OR</button>
        </div>
      )}
      {conds.map((c, i) => (
        <ConditionLeaf
          key={i}
          cond={c}
          layers={layers}
          onChange={(nc) => update(i, nc)}
          onRemove={() => remove(i)}
          canRemove={conds.length > 1}
        />
      ))}
      <button onClick={add} className="btn-outlined" style={{ alignSelf: 'flex-start' }}
              title="Weitere Bedingung hinzufügen">
        <Icon name="add" size={14} />
        <span>Bedingung</span>
      </button>
    </div>
  )
}

function ActionRow({ label, icon, active, onToggle, children }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
      <label style={{
        display: 'flex', alignItems: 'center', gap: 8,
        cursor: 'pointer', userSelect: 'none',
      }}>
        <input type="checkbox" checked={active} onChange={onToggle}
               style={{ width: 'auto', height: 'auto', padding: 0 }} />
        <Icon name={icon} size={14} style={{ color: 'var(--text-muted)' }} />
        <span style={{ fontSize: 11, color: active ? 'var(--text-primary)' : 'var(--text-muted)' }}>
          {label}
        </span>
      </label>
      {active && (
        <div style={{ marginLeft: 26, display: 'flex', gap: 6, alignItems: 'center' }}>
          {children}
        </div>
      )}
    </div>
  )
}

function ActionsEditor({ actions, linetypes, hatchPatterns, onChange }) {
  const a = actions || {}
  const setProp = (key, val) => {
    const next = { ...a }
    if (val === '' || val === null || val === undefined) {
      delete next[key]
    } else {
      next[key] = val
    }
    onChange(next)
  }
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
      <ActionRow
        label="Farbe" icon="palette"
        active={'color' in a}
        onToggle={(e) => setProp('color', e.target.checked ? (a.color || '#888888') : '')}
      >
        <input
          type="color"
          value={a.color || '#888888'}
          onChange={(e) => setProp('color', e.target.value)}
          style={{ width: 36, height: 26, padding: 2, flexShrink: 0 }}
        />
        <input
          type="text"
          value={a.color || ''}
          placeholder="#rrggbb"
          onChange={(e) => setProp('color', e.target.value)}
          style={{ flex: 1, minWidth: 0 }}
        />
      </ActionRow>

      <ActionRow
        label="Strichstärke" icon="line_weight"
        active={'lineweight' in a}
        onToggle={(e) => setProp('lineweight', e.target.checked ? (a.lineweight ?? 0.25) : '')}
      >
        <input
          type="number" step={0.05} min={0}
          value={a.lineweight ?? ''}
          onChange={(e) => setProp('lineweight', parseFloat(e.target.value) || 0)}
          style={{ width: 80 }}
        />
        <span style={{ fontSize: 10, color: 'var(--text-muted)' }}>mm</span>
      </ActionRow>

      <ActionRow
        label="Linientyp" icon="more_horiz"
        active={'linetype' in a}
        onToggle={(e) => setProp('linetype', e.target.checked ? (a.linetype || 'Continuous') : '')}
      >
        <select
          value={a.linetype || ''}
          onChange={(e) => setProp('linetype', e.target.value)}
          style={{ flex: 1, minWidth: 0 }}
        >
          <option value="">—</option>
          {(linetypes || []).map(lt => <option key={lt} value={lt}>{lt}</option>)}
        </select>
      </ActionRow>

      <ActionRow
        label="Schraffur" icon="grid_view"
        active={'hatchPattern' in a}
        onToggle={(e) => setProp('hatchPattern', e.target.checked ? (a.hatchPattern || 'Solid') : '')}
      >
        <select
          value={a.hatchPattern || ''}
          onChange={(e) => setProp('hatchPattern', e.target.value)}
          style={{ flex: 1, minWidth: 0 }}
        >
          <option value="">—</option>
          {(hatchPatterns || []).map(hp => <option key={hp} value={hp}>{hp}</option>)}
        </select>
      </ActionRow>

      <ActionRow
        label="Schraffur-Skala" icon="aspect_ratio"
        active={'hatchScale' in a}
        onToggle={(e) => setProp('hatchScale', e.target.checked ? (a.hatchScale ?? 1.0) : '')}
      >
        <input
          type="number" step={0.1} min={0.001}
          value={a.hatchScale ?? ''}
          onChange={(e) => setProp('hatchScale', parseFloat(e.target.value) || 1.0)}
          style={{ width: 80 }}
        />
      </ActionRow>

      <div style={{ fontSize: 9, color: 'var(--text-muted)', fontStyle: 'italic', lineHeight: 1.4 }}>
        Hatch-Override modifiziert nur existierende Schraffuren. Curves ohne Hatch bleiben unverändert.
      </div>
    </div>
  )
}

function RuleCard({ rule, index, total, layers, linetypes, hatchPatterns, onPatch, onDelete, onDuplicate, onMoveUp, onMoveDown, onContextMenu }) {
  const [open, setOpen] = useState(false)

  const summarize = () => {
    const conds = (rule.conditions && rule.conditions.length > 0)
      ? rule.conditions
      : (rule.condition ? [rule.condition] : [])
    const logic = (rule.conditionsLogic || 'and').toUpperCase()
    const a = rule.actions || {}
    const parts = []
    const condTexts = conds.map(c => {
      if (c.type === 'layer_name')  return `Layer ${c.operator} "${c.value || '?'}"`
      if (c.type === 'user_string') return `${c.key || '?'} ${c.operator} "${c.value || '?'}"`
      if (c.type === 'object_name') return `Name ${c.operator} "${c.value || '?'}"`
      return ''
    }).filter(Boolean)
    if (condTexts.length === 1) parts.push(condTexts[0])
    else if (condTexts.length > 1) parts.push(condTexts.join(` ${logic} `))
    const acts = Object.keys(a)
    if (acts.length) parts.push('→ ' + acts.join(', '))
    return parts.join('  ')
  }

  return (
    <div
      onContextMenu={(ev) => { if (onContextMenu) { ev.preventDefault(); onContextMenu(ev) } }}
      style={{
      border: '1px solid var(--border)', borderRadius: 'var(--r-lg)',
      background: 'var(--bg-section)', padding: 8,
      marginBottom: 8,
      opacity: rule.enabled === false ? 0.5 : 1,
    }}>
      {/* Row 1: index + checkbox + name + edit-toggle */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
        <span className="chip" style={{ flexShrink: 0 }}>#{index + 1}</span>
        <input
          type="checkbox"
          checked={rule.enabled !== false}
          onChange={(e) => onPatch({ ...rule, enabled: e.target.checked })}
          title="Regel aktiv"
          style={{ flexShrink: 0, width: 'auto', height: 'auto', padding: 0 }}
        />
        <input
          type="text"
          value={rule.name || ''}
          placeholder="Regel-Name"
          onChange={(e) => onPatch({ ...rule, name: e.target.value })}
          style={{ flex: 1, minWidth: 0 }}
        />
        <button onClick={() => setOpen(!open)} className="btn-icon"
                title={open ? 'Einklappen' : 'Bearbeiten'}>
          <Icon name={open ? 'expand_less' : 'edit'} size={14} />
        </button>
      </div>

      {!open && (
        <div style={{ fontSize: 10, color: 'var(--text-muted)', marginTop: 6, marginLeft: 4,
                      overflowWrap: 'break-word', wordBreak: 'break-word' }}>
          {summarize() || '(leer)'}
        </div>
      )}

      {open && (
        <>
          <div style={{ display: 'flex', alignItems: 'center', gap: 2, marginTop: 8 }}>
            <button onClick={() => onMoveUp()} disabled={index === 0}
                    className="btn-icon-sm" title="Prio höher (nach oben)">
              <Icon name="arrow_upward" size={14} />
            </button>
            <button onClick={() => onMoveDown()} disabled={index === total - 1}
                    className="btn-icon-sm" title="Prio tiefer (nach unten)">
              <Icon name="arrow_downward" size={14} />
            </button>
            <button onClick={() => onDuplicate()} className="btn-icon-sm" title="Duplizieren">
              <Icon name="content_copy" size={14} />
            </button>
            <div style={{ flex: 1 }} />
            <button onClick={() => { if (confirm(`Regel "${rule.name}" löschen?`)) onDelete() }}
                    className="btn-icon-danger" title="Löschen">
              <Icon name="delete" size={14} />
            </button>
          </div>

          <div style={{ marginTop: 10, display: 'flex', flexDirection: 'column', gap: 10 }}>
            <div>
              <div style={{ ...labelXs, marginBottom: 6 }}>Bedingungen</div>
              <ConditionsEditor rule={rule} layers={layers} onChange={onPatch} />
            </div>
            <div>
              <div style={{ ...labelXs, marginBottom: 6 }}>Überschreibungen</div>
              <ActionsEditor
                actions={rule.actions}
                linetypes={linetypes}
                hatchPatterns={hatchPatterns}
                onChange={(a) => onPatch({ ...rule, actions: a })}
              />
            </div>
          </div>
        </>
      )}
    </div>
  )
}

// ---------------------------------------------------------------------------

export default function OverridesApp() {
  const [state, setState] = useState({
    enabled: false, rules: [], layers: [], linetypes: [], hatchPatterns: [], presets: [],
    activePreset: null, ruleTemplates: [],
  })
  const [selectedPreset, setSelectedPreset] = useState('')
  const [selectedTemplate, setSelectedTemplate] = useState('')
  const [ctxMenu, setCtxMenu] = useState(null)  // {x, y, ruleId}

  useEffect(() => {
    onMessage('STATE', (s) => {
      setState((prev) => ({ ...prev, ...s }))
      // Dropdown synct sich auf das Backend-activePreset nur wenn der wert
      // gesetzt ist (z.B. nachdem Topbar eine Kombination geladen hat).
      // Wenn activePreset null wird (Rules wurden gerade editiert -> variant C),
      // BEHALTEN wir die lokale Auswahl — sonst weiss der Save-Button nicht
      // mehr in welche Kombination der User gerade editiert.
      if (s && s.activePreset) {
        setSelectedPreset(s.activePreset)
      }
    })
    notifyReady()
  }, [])

  const onPatch = (rule) => updateRule(rule.id, rule)
  const onMove = (id, delta) => {
    const ids = state.rules.map(r => r.id)
    const i = ids.indexOf(id)
    const j = i + delta
    if (i < 0 || j < 0 || j >= ids.length) return
    const next = ids.slice()
    next.splice(j, 0, next.splice(i, 1)[0])
    reorderRules(next)
  }

  // Kontextmenue fuer eine Regel — analog Ausschnitte/Ebenen.
  const ruleCtxItems = (ruleId) => {
    const rule = (state.rules || []).find(r => r.id === ruleId)
    if (!rule) return []
    const i = state.rules.findIndex(r => r.id === ruleId)
    const enabled = rule.enabled !== false
    return [
      { label: enabled ? 'Deaktivieren' : 'Aktivieren',
        icon: enabled ? 'visibility_off' : 'visibility',
        onClick: () => updateRule(ruleId, { ...rule, enabled: !enabled }) },
      { divider: true },
      { label: 'Prio hoeher (nach oben)',
        icon: 'arrow_upward', disabled: i <= 0,
        onClick: () => onMove(ruleId, -1) },
      { label: 'Prio tiefer (nach unten)',
        icon: 'arrow_downward', disabled: i >= state.rules.length - 1,
        onClick: () => onMove(ruleId, +1) },
      { divider: true },
      { label: 'Duplizieren',
        icon: 'content_copy',
        onClick: () => duplicateRule(ruleId) },
      { label: 'Als Vorlage speichern…',
        icon: 'bookmark_add',
        onClick: () => {
          const def = rule.name || 'Vorlage'
          const name = window.prompt('Name für Vorlage:', def)
          if (!name || !name.trim()) return
          saveRuleTemplate(name.trim(), rule)
        } },
      { divider: true },
      { label: 'Löschen',
        icon: 'delete', danger: true,
        onClick: () => {
          if (window.confirm(`Regel "${rule.name || '(ohne Name)'}" löschen?`)) deleteRule(ruleId)
        } },
    ]
  }


  return (
    <div style={{
      width: '100%', height: '100%',
      display: 'flex', flexDirection: 'column',
      padding: 10, gap: 10,
      fontFamily: 'var(--font)', color: 'var(--text-primary)',
      background: 'var(--bg-base)',
      boxSizing: 'border-box',
    }}>
      {/* Override-Kombinationen — Dropdown plus kontextabhaengiger Save.
          Globaler AN/AUS-Toggle ist jetzt in der Oberleiste, hier ueber-
          fluessig. Reapply-Button raus: Backend re-applied automatisch
          bei jeder Aenderung. */}
      <div style={{
        display: 'flex', flexDirection: 'column', gap: 6,
        padding: 10,
        background: 'var(--bg-section)',
        border: '1px solid var(--border)',
        borderRadius: 'var(--r-lg)',
      }}>
        <span style={labelXs}>Override-Kombinationen</span>
        <select
          value={selectedPreset}
          onChange={(e) => {
            const v = e.target.value
            setSelectedPreset(v)
            if (v) {
              loadPreset(v, 'replace')
            } else {
              clearOverrideRules()
            }
          }}
          style={{ width: '100%' }}
          title="Kombination zum Bearbeiten oeffnen"
        >
          <option value="">— neu / keine —</option>
          {(state.presets || []).map(p => (
            <option key={p.name} value={p.name}>
              {p.name} ({p.ruleCount})
            </option>
          ))}
        </select>
        <div style={{ display: 'flex', gap: 6 }}>
          <button
            onClick={() => {
              if (selectedPreset) { savePreset(selectedPreset); return }
              const existing = (state.presets || []).map(p => p.name)
              const def = `Kombination ${existing.length + 1}`
              const name = window.prompt('Name für neue Kombination:', def)
              if (!name || !name.trim()) return
              const t = name.trim()
              if (existing.includes(t) && !window.confirm(`Kombination "${t}" überschreiben?`)) return
              savePreset(t)
              setSelectedPreset(t)
            }}
            disabled={state.rules.length === 0}
            className="btn-outlined"
            style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6 }}
            title={selectedPreset
              ? `Änderungen in "${selectedPreset}" speichern`
              : 'Aktuelle Regeln als neue Kombination speichern'}
          >
            <Icon name="save" size={14} />
            <span>{selectedPreset ? 'Speichern' : 'Als Kombination speichern…'}</span>
          </button>
          <button
            onClick={() => {
              if (!selectedPreset) return
              if (!window.confirm(`Kombination "${selectedPreset}" dauerhaft loeschen?`)) return
              deletePreset(selectedPreset)
              setSelectedPreset('')
            }}
            disabled={!selectedPreset}
            className="btn-icon-danger"
            title="Gewaehlte Kombination dauerhaft loeschen"
          >
            <Icon name="delete" size={14} />
          </button>
        </div>
      </div>

      {/* Neue Regel: leere Regel ODER aus Vorlage. */}
      <div style={{
        display: 'flex', alignItems: 'center', gap: 6,
        padding: '8px 10px',
        background: 'var(--bg-section)',
        border: '1px solid var(--border)',
        borderRadius: 'var(--r-lg)',
      }}>
        <button
          onClick={() => addRule({})}
          className="btn-add"
          title="Leere Regel oben einfuegen"
        >
          <Icon name="add" size={16} />
        </button>
        <select
          value={selectedTemplate}
          onChange={(e) => {
            const v = e.target.value
            if (!v) { setSelectedTemplate(''); return }
            if (v === '__delete__') {
              if (!selectedTemplate) return
              if (!window.confirm(`Vorlage "${selectedTemplate}" dauerhaft loeschen?`)) return
              deleteRuleTemplate(selectedTemplate)
              setSelectedTemplate('')
              return
            }
            addFromTemplate(v)
            setSelectedTemplate(v)
          }}
          style={{ flex: 1, minWidth: 0 }}
          title="Regel aus Vorlage einfuegen"
        >
          <option value="">+ Aus Vorlage…</option>
          {(state.ruleTemplates || []).map(t => (
            <option key={t.name} value={t.name}>{t.name}</option>
          ))}
          {selectedTemplate && (state.ruleTemplates || []).some(t => t.name === selectedTemplate) && (
            <>
              <option disabled>──────────</option>
              <option value="__delete__">🗑 "{selectedTemplate}" loeschen</option>
            </>
          )}
        </select>
      </div>

      <div style={{ fontSize: 10, color: 'var(--text-muted)', fontStyle: 'italic', lineHeight: 1.4 }}>
        Regeln sind additiv. Bei Konflikt gewinnt die <b>oberste</b>.
      </div>

      {/* Rule list */}
      <div style={{ flex: 1, overflowY: 'auto', overflowX: 'hidden', minHeight: 0 }}>
        {(state.rules || []).length === 0 && (
          <div style={{
            padding: '32px 16px', textAlign: 'center',
            color: 'var(--text-muted)', fontSize: 11,
            border: '1px dashed var(--border)',
            borderRadius: 'var(--r-lg)',
            background: 'var(--bg-section)',
          }}>
            <Icon name="auto_fix_high" size={32} style={{ color: 'var(--text-muted)', opacity: 0.5 }} />
            <div style={{ marginTop: 8 }}>Noch keine Regeln.</div>
            <div style={{ marginTop: 4, fontSize: 10 }}>
              Oben <Icon name="add" size={11} /> klicken um eine neue Regel zu erstellen.
            </div>
          </div>
        )}
        {(state.rules || []).map((r, i) => (
          <RuleCard
            key={r.id}
            rule={r}
            index={i}
            total={state.rules.length}
            layers={state.layers}
            linetypes={state.linetypes}
            hatchPatterns={state.hatchPatterns}
            onPatch={onPatch}
            onDelete={() => deleteRule(r.id)}
            onDuplicate={() => duplicateRule(r.id)}
            onMoveUp={() => onMove(r.id, -1)}
            onMoveDown={() => onMove(r.id, +1)}
            onContextMenu={(ev) => setCtxMenu({ x: ev.clientX, y: ev.clientY, ruleId: r.id })}
          />
        ))}
      </div>
      {ctxMenu && (
        <ContextMenu
          x={ctxMenu.x}
          y={ctxMenu.y}
          items={ruleCtxItems(ctxMenu.ruleId)}
          onClose={() => setCtxMenu(null)}
        />
      )}
    </div>
  )
}
