import { useEffect, useState } from 'react'
import { onMessage, notifyReady } from './lib/rhinoBridge'

function send(type, payload = {}) {
  if (!window.RHINO_MODE) { console.log('[AusschnittSettings] →', type, payload); return }
  document.title = 'RHINOMSG::' + JSON.stringify({ type, payload })
}

function Field({ label, hint, children }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 3, padding: '6px 0' }}>
      <span style={{ fontSize: 10, color: 'var(--text-secondary)',
                     fontWeight: 500, letterSpacing: 0.2 }}>
        {label}
      </span>
      <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>{children}</div>
      {hint && (
        <span style={{ fontSize: 9, color: 'var(--text-muted)', lineHeight: 1.4 }}>{hint}</span>
      )}
    </div>
  )
}

function SectionLabel({ children }) {
  return (
    <div style={{
      fontSize: 9, color: 'var(--text-muted)', fontWeight: 600,
      letterSpacing: 0.5, textTransform: 'uppercase',
      padding: '10px 0 4px',
      borderTop: '1px solid var(--border-light)',
      marginTop: 8,
    }}>{children}</div>
  )
}

export default function AusschnittSettingsApp() {
  const initial = (typeof window !== 'undefined' && window.PANEL_PARAMS) || {}
  const [snap, setSnap]                       = useState(initial.snap || {})
  const [displayModes, setDisplayModes]       = useState(initial.displayModes || [])
  const [overridesPresets, setOverridesPresets] = useState(initial.overridesPresets || [])
  const [layerKombis, setLayerKombis]         = useState(initial.layerKombis || [])

  useEffect(() => {
    onMessage('AUSSCHNITT_SETTINGS_STATE', (p) => {
      if (p.snap) setSnap(p.snap)
      if (Array.isArray(p.displayModes))     setDisplayModes(p.displayModes)
      if (Array.isArray(p.overridesPresets)) setOverridesPresets(p.overridesPresets)
      if (Array.isArray(p.layerKombis))      setLayerKombis(p.layerKombis)
    })
    notifyReady()
    const blockContext = (ev) => ev.preventDefault()
    document.addEventListener('contextmenu', blockContext)
    return () => document.removeEventListener('contextmenu', blockContext)
  }, [])

  const set = (patch) => setSnap(s => ({ ...s, ...patch }))

  const saveAndClose = () => {
    send('SAVE', {
      settings: {
        scale:             snap.scale || '',
        displayMode:       snap.displayMode || null,
        displayModeName:   snap.displayModeName || null,
        applyOverrides:    !!snap.applyOverrides,
        overridesEnabled:  !!snap.overridesEnabled,
        overridesPreset:   snap.overridesPreset || '',
        layerCombination:  snap.layerCombination || '',
        darstellung:       snap.darstellung || '',
      },
    })
  }

  return (
    <div style={{
      position: 'absolute', inset: 0,
      background: 'var(--bg-dialog)',
      display: 'flex', flexDirection: 'column',
      fontFamily: 'var(--font)', color: 'var(--text-primary)',
      overflow: 'hidden',
    }}>
      {/* Body */}
      <div style={{ flex: 1, overflowY: 'auto', padding: '8px 14px' }}>
        <Field label="MASSSTAB" hint="z.B. 1:50 — leer für unverändert">
          <input
            value={snap.scale || ''}
            onChange={(ev) => set({ scale: ev.target.value })}
            placeholder="1:50"
            style={{ flex: 1, fontSize: 11, fontFamily: 'var(--font-mono)', minWidth: 0 }}
          />
        </Field>

        <Field label="DARSTELLUNG"
               hint="SIA-400 Detaillierungsgrad fuer diesen Ausschnitt — leer = beim Restore nicht aendern">
          <select
            value={snap.darstellung || ''}
            onChange={(ev) => set({ darstellung: ev.target.value })}
            style={{ flex: 1, fontSize: 11, minWidth: 0 }}
          >
            <option value="">— nicht aendern —</option>
            <option value="einfach">Einfach (1:100)</option>
            <option value="standard">Standard (1:50)</option>
            <option value="detail">Detail (1:20)</option>
          </select>
        </Field>

        <Field label="BILDSCHIRMMODUS"
               hint="Display-Mode des Viewports beim Wiederherstellen">
          <select
            value={snap.displayMode || ''}
            onChange={(ev) => {
              const dm = displayModes.find(d => d.id === ev.target.value)
              set({
                displayMode:     ev.target.value || null,
                displayModeName: dm ? dm.name : null,
              })
            }}
            style={{ flex: 1, fontSize: 11, minWidth: 0 }}
          >
            <option value="">— unverändert —</option>
            {displayModes.map(dm => (
              <option key={dm.id} value={dm.id}>{dm.name}</option>
            ))}
          </select>
        </Field>

        <SectionLabel>Grafische Overrides</SectionLabel>

        <Field label="OVERRIDES BEIM RESTORE">
          <input
            type="checkbox"
            checked={!!snap.applyOverrides}
            onChange={(ev) => set({ applyOverrides: ev.target.checked })}
            style={{ marginRight: 6 }}
          />
          <span style={{ fontSize: 10, color: 'var(--text-muted)', flex: 1 }}>
            {snap.applyOverrides
              ? 'Overrides werden gesetzt'
              : 'Aktueller Overrides-Zustand bleibt'}
          </span>
        </Field>

        {snap.applyOverrides && (
          <>
            <Field label="OVERRIDES STATUS">
              <select
                value={snap.overridesEnabled ? 'on' : 'off'}
                onChange={(ev) => set({ overridesEnabled: ev.target.value === 'on' })}
                style={{ flex: 1, fontSize: 11, minWidth: 0 }}
              >
                <option value="on">AN</option>
                <option value="off">AUS</option>
              </select>
            </Field>

            <Field label="OVERRIDES PRESET"
                   hint="Leer = kein Preset (Doc-Rules bleiben)">
              <select
                value={snap.overridesPreset || ''}
                onChange={(ev) => set({ overridesPreset: ev.target.value })}
                style={{ flex: 1, fontSize: 11, minWidth: 0 }}
                disabled={!snap.overridesEnabled}
              >
                <option value="">— kein Preset —</option>
                {overridesPresets.map(name => (
                  <option key={name} value={name}>{name}</option>
                ))}
              </select>
            </Field>
          </>
        )}

        <SectionLabel>Ebenenkombination</SectionLabel>

        <Field label="KOMBI"
               hint='"Eigene" = die per Snap gespeicherte Sichtbarkeit. Ein Preset überschreibt diese beim Wiederherstellen.'>
          <select
            value={snap.layerCombination || ''}
            onChange={(ev) => set({ layerCombination: ev.target.value })}
            style={{ flex: 1, fontSize: 11, minWidth: 0 }}
          >
            <option value="">— Eigene Sichtbarkeit —</option>
            {layerKombis.map(name => (
              <option key={name} value={name}>{name}</option>
            ))}
          </select>
        </Field>
      </div>

      {/* Footer */}
      <div style={{
        display: 'flex', alignItems: 'center', gap: 6,
        padding: '8px 12px',
        borderTop: '1px solid var(--border)',
        background: 'var(--bg-section)',
      }}>
        <div style={{ flex: 1 }} />
        <button className="btn-text" onClick={() => send('CANCEL', {})}>Abbrechen</button>
        <button className="btn-contained" onClick={saveAndClose}>Übernehmen</button>
      </div>
    </div>
  )
}
