import { useEditor, useValue } from 'tldraw'
import { useCallback } from 'react'
import { PUFFER_CONFIG, KREISEL_CONFIG, FOERDERER_CONFIG } from '../shapes/shape-config'

/** Nächste freie Nummer für einen Shape-Typ ermitteln. */
function nextNumber(editor: ReturnType<typeof useEditor>, type: string): number {
  const existing = editor.getCurrentPageShapes().filter((s) => s.type === type)
  // Höchste bestehende Nummer finden
  let max = 0
  for (const s of existing) {
    const lbl = (s.props as { label?: string }).label ?? ''
    const m = lbl.match(/_(\d+)$/)
    if (m) max = Math.max(max, parseInt(m[1], 10))
  }
  return max + 1
}

/**
 * Panel links oben: Buttons zum Erstellen von Symbolen + Sync zum Server.
 * Wird als Kind von <Tldraw> gerendert, daher ist useEditor() verfügbar.
 */
export function ShapePanel() {
  const editor = useEditor()

  const createPuffer = useCallback(() => {
    const nr = nextNumber(editor, 'puffer')
    const center = editor.getViewportScreenCenter()
    const point = editor.screenToPage(center)
    editor.createShape({
      type: 'puffer',
      x: point.x - PUFFER_CONFIG.defaultW / 2,
      y: point.y - PUFFER_CONFIG.defaultH / 2,
      props: {
        w: PUFFER_CONFIG.defaultW,
        h: PUFFER_CONFIG.defaultH,
        label: `Puffer_${nr}`,
      },
    })
  }, [editor])

  const createKreisel = useCallback(() => {
    const nr = nextNumber(editor, 'kreisel')
    const center = editor.getViewportScreenCenter()
    const point = editor.screenToPage(center)
    const totalW = 2 * KREISEL_CONFIG.defaultRadius + KREISEL_CONFIG.defaultAbstand
    const totalH = 2 * KREISEL_CONFIG.defaultRadius
    editor.createShape({
      type: 'kreisel',
      x: point.x - totalW / 2,
      y: point.y - totalH / 2,
      props: {
        abstand: KREISEL_CONFIG.defaultAbstand,
        radius: KREISEL_CONFIG.defaultRadius,
        label: `Kreisel_${nr}`,
      },
    })
  }, [editor])

  const createFoerderer = useCallback(() => {
    const nr = nextNumber(editor, 'foerderer')
    const center = editor.getViewportScreenCenter()
    const point = editor.screenToPage(center)
    editor.createShape({
      type: 'foerderer',
      x: point.x - FOERDERER_CONFIG.defaultEndX / 2,
      y: point.y,
      props: {
        endX: FOERDERER_CONFIG.defaultEndX,
        endY: FOERDERER_CONFIG.defaultEndY,
        spacing: FOERDERER_CONFIG.defaultSpacing,
        label: `Förderer_${nr}`,
      },
    })
  }, [editor])

  const activatePolylinie = useCallback(() => {
    editor.setCurrentTool('polylinie')
  }, [editor])

  const currentToolId = useValue('current tool', () => editor.getCurrentToolId(), [editor])
  const isPolylinieActive = currentToolId === 'polylinie'

  const syncToServer = useCallback(async () => {
    const allShapes = editor.getCurrentPageShapes()

    const puffer = allShapes
      .filter((s) => s.type === 'puffer')
      .map((s) => {
        const p = s.props as { w: number; h: number }
        return { id: s.id, x: s.x, y: s.y, w: p.w, h: p.h }
      })

    const kreisel = allShapes
      .filter((s) => s.type === 'kreisel')
      .map((s) => {
        const p = s.props as { abstand: number; radius: number }
        return { id: s.id, x: s.x, y: s.y, abstand: p.abstand, radius: p.radius }
      })

    try {
      const res = await fetch('/api/shapes/update', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ puffer, kreisel }),
      })
      const data = await res.json()
      console.log('Server response:', data)
      alert(`Sync OK – ${data.received.puffer_count} Puffer, ${data.received.kreisel_count} Kreisel`)
    } catch (err) {
      console.error('Sync error:', err)
      alert('Sync fehlgeschlagen – siehe Konsole')
    }
  }, [editor])

  return (
    <div style={panelStyle}>
      <div style={{ fontWeight: 'bold', fontSize: 13, marginBottom: 4 }}>
        Symbole
      </div>
      <button onClick={createPuffer} style={btnStyle}>
        ▭ Puffer
      </button>
      <button onClick={createKreisel} style={btnStyle}>
        ◎ Kreisel
      </button>
      <button onClick={createFoerderer} style={btnStyle}>
        ═ Förderer
      </button>
      <button
        onClick={activatePolylinie}
        style={{
          ...btnStyle,
          background: isPolylinieActive ? '#404040' : '#f8f8f8',
          color: isPolylinieActive ? 'white' : 'inherit',
        }}
      >
        ⚡ Polylinie
      </button>
      <hr style={{ width: '100%', margin: '4px 0' }} />
      <button onClick={syncToServer} style={{ ...btnStyle, background: '#e0f0ff' }}>
        ↑ Sync Server
      </button>
    </div>
  )
}

const panelStyle: React.CSSProperties = {
  position: 'absolute',
  top: 60,
  left: 10,
  zIndex: 1000,
  display: 'flex',
  flexDirection: 'column',
  gap: 6,
  background: 'white',
  padding: 10,
  borderRadius: 8,
  boxShadow: '0 2px 8px rgba(0,0,0,0.15)',
}

const btnStyle: React.CSSProperties = {
  padding: '6px 12px',
  cursor: 'pointer',
  border: '1px solid #ccc',
  borderRadius: 4,
  background: '#f8f8f8',
  fontSize: 13,
}
