import { useState, useEffect } from 'react'
import { api } from '../utils/api'
import { Search, X } from 'lucide-react'

/**
 * Placeholder Picker with grouped categories and search
 *
 * Loads placeholders dynamically from backend catalog.
 * Grouped by category (Profil, Körper, Ernährung, Training, etc.)
 */
export default function PlaceholderPicker({ onSelect, onClose }) {
  const [catalog, setCatalog] = useState({})
  const [search, setSearch] = useState('')
  const [loading, setLoading] = useState(true)
  const [expandedCategories, setExpandedCategories] = useState(new Set())

  useEffect(() => {
    loadCatalog()
  }, [])

  const loadCatalog = async () => {
    try {
      setLoading(true)
      const data = await api.listPlaceholders()
      setCatalog(data)
      // Expand all categories by default
      setExpandedCategories(new Set(Object.keys(data)))
    } catch (e) {
      console.error('Failed to load placeholders:', e)
    } finally {
      setLoading(false)
    }
  }

  const toggleCategory = (category) => {
    const newExpanded = new Set(expandedCategories)
    if (newExpanded.has(category)) {
      newExpanded.delete(category)
    } else {
      newExpanded.add(category)
    }
    setExpandedCategories(newExpanded)
  }

  const handleSelect = (key) => {
    onSelect(`{{${key}}}`)
    onClose()
  }

  // Filter placeholders by search
  const filteredCatalog = {}
  const searchLower = search.toLowerCase()

  Object.entries(catalog).forEach(([category, items]) => {
    const filtered = items.filter(item =>
      item.key.toLowerCase().includes(searchLower) ||
      item.description.toLowerCase().includes(searchLower)
    )
    if (filtered.length > 0) {
      filteredCatalog[category] = filtered
    }
  })

  return (
    <div
      style={{
        position: 'fixed',
        inset: 0,
        background: 'rgba(0,0,0,0.5)',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        zIndex: 2000,
        padding: 20
      }}
      onClick={onClose}
    >
      <div
        onClick={e => e.stopPropagation()}
        style={{
          background: 'var(--bg)',
          borderRadius: 12,
          maxWidth: 800,
          width: '100%',
          maxHeight: '80vh',
          display: 'flex',
          flexDirection: 'column',
          overflow: 'hidden'
        }}
      >
        {/* Header */}
        <div style={{
          padding: 20,
          borderBottom: '1px solid var(--border)',
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center'
        }}>
          <h3 style={{ margin: 0, fontSize: 18, fontWeight: 600 }}>
            Platzhalter auswählen
          </h3>
          <button
            onClick={onClose}
            style={{ background: 'none', border: 'none', cursor: 'pointer', padding: 4 }}
          >
            <X size={24} color="var(--text3)" />
          </button>
        </div>

        {/* Search */}
        <div style={{ padding: '12px 20px', borderBottom: '1px solid var(--border)' }}>
          <div style={{ position: 'relative' }}>
            <Search
              size={16}
              style={{
                position: 'absolute',
                left: 12,
                top: '50%',
                transform: 'translateY(-50%)',
                color: 'var(--text3)'
              }}
            />
            <input
              type="text"
              className="form-input"
              value={search}
              onChange={e => setSearch(e.target.value)}
              placeholder="Platzhalter suchen..."
              style={{
                width: '100%',
                paddingLeft: 40,
                textAlign: 'left'
              }}
            />
          </div>
        </div>

        {/* Categories */}
        <div style={{
          flex: 1,
          overflow: 'auto',
          padding: 20
        }}>
          {loading ? (
            <div style={{ textAlign: 'center', padding: 40, color: 'var(--text3)' }}>
              Lädt Platzhalter...
            </div>
          ) : Object.keys(filteredCatalog).length === 0 ? (
            <div style={{ textAlign: 'center', padding: 40, color: 'var(--text3)' }}>
              Keine Platzhalter gefunden
            </div>
          ) : (
            Object.entries(filteredCatalog).map(([category, items]) => (
              <div key={category} style={{ marginBottom: 16 }}>
                <div
                  onClick={() => toggleCategory(category)}
                  style={{
                    padding: '8px 12px',
                    background: 'var(--surface)',
                    borderRadius: 8,
                    cursor: 'pointer',
                    display: 'flex',
                    justifyContent: 'space-between',
                    alignItems: 'center',
                    marginBottom: 8
                  }}
                >
                  <h4 style={{ margin: 0, fontSize: 14, fontWeight: 600 }}>
                    {category} ({items.length})
                  </h4>
                  <span style={{ fontSize: 12, color: 'var(--text3)' }}>
                    {expandedCategories.has(category) ? '▼' : '▶'}
                  </span>
                </div>

                {expandedCategories.has(category) && (
                  <div style={{ display: 'grid', gap: 6, paddingLeft: 12 }}>
                    {items.map(item => (
                      <div
                        key={item.key}
                        onClick={() => handleSelect(item.key)}
                        style={{
                          padding: '8px 12px',
                          background: 'var(--surface2)',
                          borderRadius: 6,
                          cursor: 'pointer',
                          border: '1px solid transparent',
                          transition: 'all 0.2s'
                        }}
                        onMouseEnter={e => {
                          e.currentTarget.style.borderColor = 'var(--accent)'
                          e.currentTarget.style.background = 'var(--surface)'
                        }}
                        onMouseLeave={e => {
                          e.currentTarget.style.borderColor = 'transparent'
                          e.currentTarget.style.background = 'var(--surface2)'
                        }}
                      >
                        <div>
                          <div>
                            <code style={{
                              fontSize: 12,
                              fontWeight: 600,
                              color: 'var(--accent)',
                              fontFamily: 'monospace'
                            }}>
                              {`{{${item.key}}}`}
                            </code>
                            <div style={{
                              fontSize: 11,
                              color: 'var(--text2)',
                              marginTop: 2
                            }}>
                              {item.description}
                            </div>
                          </div>
                          {item.example && (
                            <div style={{
                              fontSize: 11,
                              color: 'var(--text3)',
                              fontFamily: 'monospace',
                              padding: '4px 8px',
                              background: 'var(--bg)',
                              borderRadius: 4,
                              marginTop: 6,
                              wordBreak: 'break-word'
                            }}>
                              <span style={{ fontSize: 9, opacity: 0.7, marginRight: 4 }}>Beispiel:</span>
                              {item.example}
                            </div>
                          )}
                        </div>
                      </div>
                    ))}
                  </div>
                )}
              </div>
            ))
          )}
        </div>

        {/* Footer */}
        <div style={{
          padding: 16,
          borderTop: '1px solid var(--border)',
          textAlign: 'center',
          fontSize: 11,
          color: 'var(--text3)'
        }}>
          Klicke auf einen Platzhalter zum Einfügen
        </div>
      </div>
    </div>
  )
}
