import { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { Pencil, Trash2, Plus, Save, X, ArrowLeft, Settings } from 'lucide-react'
import { api } from '../utils/api'
import ProfileBuilder from '../components/ProfileBuilder'
import EmojiIconPicker from '../components/EmojiIconPicker'

/**
 * AdminTrainingTypesPage - CRUD for training types
 * v9d Phase 1b - Basic CRUD without abilities mapping
 */
export default function AdminTrainingTypesPage() {
  const nav = useNavigate()
  const [types, setTypes] = useState([])
  const [categories, setCategories] = useState({})
  const [loading, setLoading] = useState(true)
  const [editingId, setEditingId] = useState(null)
  const [formData, setFormData] = useState(null)
  const [error, setError] = useState(null)
  const [saving, setSaving] = useState(false)
  const [editingProfileId, setEditingProfileId] = useState(null)
  const [parameters, setParameters] = useState([])

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

  const load = () => {
    setLoading(true)
    Promise.all([
      api.adminListTrainingTypes(),
      api.getTrainingCategories(),
      api.getTrainingParameters()
    ]).then(([typesData, catsData, paramsData]) => {
      setTypes(typesData)
      setCategories(catsData)
      setParameters(paramsData.parameters || [])
      setLoading(false)
    }).catch(err => {
      console.error('Failed to load training types:', err)
      setError(err.message)
      setLoading(false)
    })
  }

  const startCreate = () => {
    setFormData({
      category: 'cardio',
      subcategory: '',
      name_de: '',
      name_en: '',
      icon: '',
      description_de: '',
      description_en: '',
      sort_order: 0
    })
    setEditingId('new')
  }

  const startEdit = (type) => {
    setFormData({
      category: type.category,
      subcategory: type.subcategory || '',
      name_de: type.name_de,
      name_en: type.name_en,
      icon: type.icon || '',
      description_de: type.description_de || '',
      description_en: type.description_en || '',
      sort_order: type.sort_order
    })
    setEditingId(type.id)
  }

  const cancelEdit = () => {
    setEditingId(null)
    setFormData(null)
    setError(null)
  }

  const handleSave = async () => {
    if (!formData.name_de || !formData.name_en) {
      setError('Name (DE) und Name (EN) sind Pflichtfelder')
      return
    }

    setSaving(true)
    setError(null)

    try {
      if (editingId === 'new') {
        await api.adminCreateTrainingType(formData)
      } else {
        await api.adminUpdateTrainingType(editingId, formData)
      }
      await load()
      cancelEdit()
    } catch (err) {
      console.error('Save failed:', err)
      setError(err.message)
    } finally {
      setSaving(false)
    }
  }

  const handleDelete = async (id, name) => {
    if (!confirm(`Trainingstyp "${name}" wirklich löschen?\n\nHinweis: Löschen ist nur möglich wenn keine Aktivitäten diesen Typ verwenden.`)) {
      return
    }

    try {
      await api.adminDeleteTrainingType(id)
      await load()
    } catch (err) {
      alert('Löschen fehlgeschlagen: ' + err.message)
    }
  }

  const startEditProfile = (typeId) => {
    setEditingProfileId(typeId)
    setEditingId(null) // Close type editor if open
    setFormData(null)
  }

  const cancelEditProfile = () => {
    setEditingProfileId(null)
  }

  const handleSaveProfile = async (profile) => {
    try {
      await api.adminUpdateTrainingType(editingProfileId, { profile })
      await load()
      // Success message is shown by ProfileBuilder component
      // Don't close editor immediately - let user see success message
      setTimeout(() => {
        setEditingProfileId(null)
      }, 2000)
    } catch (err) {
      // Error will be thrown to ProfileBuilder
      throw err
    }
  }

  // Group by category
  const grouped = {}
  types.forEach(type => {
    if (!grouped[type.category]) {
      grouped[type.category] = []
    }
    grouped[type.category].push(type)
  })

  if (loading) {
    return (
      <div style={{ padding: 20, textAlign: 'center' }}>
        <div className="spinner" style={{ width: 32, height: 32, margin: '0 auto' }} />
      </div>
    )
  }

  return (
    <div style={{ padding: '16px 16px 80px' }}>
      <div style={{ marginBottom: 20, display: 'flex', alignItems: 'center', gap: 12 }}>
        <button
          onClick={() => nav('/settings')}
          style={{
            background: 'none',
            border: 'none',
            cursor: 'pointer',
            padding: 6,
            display: 'flex',
            color: 'var(--text2)'
          }}
        >
          <ArrowLeft size={20} />
        </button>
        <h1 style={{ margin: 0, fontSize: 20, fontWeight: 700 }}>Trainingstypen verwalten</h1>
      </div>

      {error && (
        <div className="card" style={{ padding: 12, marginBottom: 16, background: '#FCEBEB', color: '#D85A30' }}>
          {error}
        </div>
      )}

      {/* Create new button */}
      {!editingId && (
        <button
          onClick={startCreate}
          className="btn btn-primary btn-full"
          style={{ marginBottom: 16 }}
        >
          <Plus size={16} /> Neuen Trainingstyp anlegen
        </button>
      )}

      {/* Edit form (only for new type creation, at top) */}
      {editingId === 'new' && formData && (
        <div className="card" style={{ padding: 16, marginBottom: 16 }}>
          <div style={{ fontWeight: 600, marginBottom: 12 }}>
            {editingId === 'new' ? '➕ Neuer Trainingstyp' : '✏️ Trainingstyp bearbeiten'}
          </div>

          <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
            <div>
              <div className="form-label">Kategorie *</div>
              <select
                className="form-input"
                value={formData.category}
                onChange={e => setFormData({ ...formData, category: e.target.value })}
                style={{ width: '100%' }}
              >
                {Object.keys(categories).map(cat => (
                  <option key={cat} value={cat}>
                    {categories[cat].icon} {categories[cat].name_de}
                  </option>
                ))}
              </select>
            </div>

            <div>
              <div className="form-label">Subkategorie</div>
              <input
                className="form-input"
                value={formData.subcategory}
                onChange={e => setFormData({ ...formData, subcategory: e.target.value })}
                placeholder="z.B. running, hypertrophy, meditation"
                style={{ width: '100%' }}
              />
              <div style={{ fontSize: 11, color: 'var(--text3)', marginTop: 4 }}>
                Kleingeschrieben, ohne Leerzeichen, eindeutig
              </div>
            </div>

            <div>
              <div className="form-label">Name (Deutsch) *</div>
              <input
                className="form-input"
                value={formData.name_de}
                onChange={e => setFormData({ ...formData, name_de: e.target.value })}
                placeholder="z.B. Laufen"
                style={{ width: '100%' }}
              />
            </div>

            <div>
              <div className="form-label">Name (English) *</div>
              <input
                className="form-input"
                value={formData.name_en}
                onChange={e => setFormData({ ...formData, name_en: e.target.value })}
                placeholder="e.g. Running"
                style={{ width: '100%' }}
              />
            </div>

            <div>
              <div className="form-label">Icon (Emoji)</div>
              <EmojiIconPicker
                value={formData.icon}
                onChange={(icon) => setFormData({ ...formData, icon })}
                placeholder="🏃"
                maxLength={10}
              />
            </div>

            <div>
              <div className="form-label">Sortierung</div>
              <input
                type="number"
                className="form-input"
                value={formData.sort_order}
                onChange={e => setFormData({ ...formData, sort_order: parseInt(e.target.value) })}
                style={{ width: '100%' }}
              />
              <div style={{ fontSize: 11, color: 'var(--text3)', marginTop: 4 }}>
                Niedrigere Zahlen werden zuerst angezeigt
              </div>
            </div>

            <div>
              <div className="form-label">Beschreibung (Deutsch)</div>
              <textarea
                className="form-input"
                value={formData.description_de}
                onChange={e => setFormData({ ...formData, description_de: e.target.value })}
                placeholder="Optional: Beschreibung für KI-Analyse"
                rows={4}
                style={{ width: '100%', resize: 'vertical' }}
              />
            </div>

            <div>
              <div className="form-label">Beschreibung (English)</div>
              <textarea
                className="form-input"
                value={formData.description_en}
                onChange={e => setFormData({ ...formData, description_en: e.target.value })}
                placeholder="Optional: Description for AI analysis"
                rows={4}
                style={{ width: '100%', resize: 'vertical' }}
              />
            </div>

            <div style={{ display: 'flex', gap: 8, marginTop: 8 }}>
              <button
                onClick={handleSave}
                disabled={saving}
                className="btn btn-primary"
                style={{ flex: 1 }}
              >
                {saving ? (
                  <>
                    <div className="spinner" style={{ width: 14, height: 14 }} />
                    Speichere...
                  </>
                ) : (
                  <>
                    <Save size={16} /> Speichern
                  </>
                )}
              </button>
              <button
                onClick={cancelEdit}
                disabled={saving}
                className="btn btn-secondary"
                style={{ flex: 1 }}
              >
                <X size={16} /> Abbrechen
              </button>
            </div>
          </div>
        </div>
      )}

      {/* List grouped by category */}
      {Object.entries(grouped).sort((a, b) => {
        const orderA = categories[a[0]]?.sort_order || 999
        const orderB = categories[b[0]]?.sort_order || 999
        return orderA - orderB
      }).map(([cat, catTypes]) => (
        <div key={cat} className="card" style={{ padding: 16, marginBottom: 12 }}>
          <div style={{
            fontWeight: 600,
            fontSize: 14,
            marginBottom: 12,
            color: categories[cat]?.color || 'var(--text1)'
          }}>
            {categories[cat]?.icon} {categories[cat]?.name_de}
          </div>

          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {catTypes.sort((a, b) => a.sort_order - b.sort_order).map(type => (
              <div key={type.id}>
                {/* Type Row */}
                <div
                  style={{
                    display: 'flex',
                    alignItems: 'center',
                    gap: 8,
                    padding: 8,
                    background: 'var(--surface)',
                    borderRadius: 6
                  }}
                >
                  <div style={{ fontSize: 18 }}>{type.icon}</div>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 13, fontWeight: 500 }}>
                      {type.name_de} <span style={{ color: 'var(--text3)' }}>/ {type.name_en}</span>
                      {type.profile && (
                        <span style={{
                          marginLeft: 8,
                          padding: '2px 6px',
                          background: 'var(--accent)',
                          color: 'white',
                          borderRadius: 4,
                          fontSize: 10
                        }}>
                          ✓ Profil
                        </span>
                      )}
                    </div>
                    {type.subcategory && (
                      <div style={{ fontSize: 11, color: 'var(--text3)' }}>
                        Subkategorie: {type.subcategory}
                      </div>
                    )}
                  </div>
                  <button
                    onClick={() => startEditProfile(type.id)}
                    style={{
                      background: 'none',
                      border: 'none',
                      cursor: 'pointer',
                      padding: 6,
                      color: 'var(--accent)'
                    }}
                    title="Profil konfigurieren"
                  >
                    <Settings size={16} />
                  </button>
                  <button
                    onClick={() => startEdit(type)}
                    style={{
                      background: 'none',
                      border: 'none',
                      cursor: 'pointer',
                      padding: 6,
                      color: 'var(--accent)'
                    }}
                    title="Bearbeiten"
                  >
                    <Pencil size={16} />
                  </button>
                  <button
                    onClick={() => handleDelete(type.id, type.name_de)}
                    style={{
                      background: 'none',
                      border: 'none',
                      cursor: 'pointer',
                      padding: 6,
                      color: '#D85A30'
                    }}
                    title="Löschen"
                  >
                    <Trash2 size={16} />
                  </button>
                </div>

                {/* Inline Profile Builder */}
                {editingProfileId === type.id && (
                  <div style={{ marginTop: 8 }}>
                    <ProfileBuilder
                      trainingType={type}
                      parameters={parameters}
                      onSave={handleSaveProfile}
                      onCancel={cancelEditProfile}
                    />
                  </div>
                )}

                {/* Inline Type Editor */}
                {editingId === type.id && formData && (
                  <div style={{ marginTop: 8, padding: 16, background: 'var(--surface2)', borderRadius: 8 }}>
                    <div style={{ fontWeight: 600, marginBottom: 12 }}>✏️ Trainingstyp bearbeiten</div>
                    <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
                      <div>
                        <div className="form-label">Kategorie *</div>
                        <select
                          className="form-input"
                          value={formData.category}
                          onChange={e => setFormData({ ...formData, category: e.target.value })}
                          style={{ width: '100%' }}
                        >
                          {Object.keys(categories).map(cat => (
                            <option key={cat} value={cat}>
                              {categories[cat].icon} {categories[cat].name_de}
                            </option>
                          ))}
                        </select>
                      </div>

                      <div>
                        <div className="form-label">Subkategorie</div>
                        <input
                          className="form-input"
                          value={formData.subcategory}
                          onChange={e => setFormData({ ...formData, subcategory: e.target.value })}
                          placeholder="z.B. running, hypertrophy, meditation"
                          style={{ width: '100%' }}
                        />
                      </div>

                      <div>
                        <div className="form-label">Name (Deutsch) *</div>
                        <input
                          className="form-input"
                          value={formData.name_de}
                          onChange={e => setFormData({ ...formData, name_de: e.target.value })}
                          placeholder="z.B. Laufen"
                          style={{ width: '100%' }}
                        />
                      </div>

                      <div>
                        <div className="form-label">Name (English) *</div>
                        <input
                          className="form-input"
                          value={formData.name_en}
                          onChange={e => setFormData({ ...formData, name_en: e.target.value })}
                          placeholder="e.g. Running"
                          style={{ width: '100%' }}
                        />
                      </div>

                      <div>
                        <div className="form-label">Icon (Emoji)</div>
                        <EmojiIconPicker
                          value={formData.icon}
                          onChange={(icon) => setFormData({ ...formData, icon })}
                          placeholder="🏃"
                          maxLength={10}
                        />
                      </div>

                      <div>
                        <div className="form-label">Sortierung</div>
                        <input
                          type="number"
                          className="form-input"
                          value={formData.sort_order}
                          onChange={e => setFormData({ ...formData, sort_order: parseInt(e.target.value) })}
                          style={{ width: '100%' }}
                        />
                      </div>

                      <div style={{ display: 'flex', gap: 8 }}>
                        <button onClick={handleSave} disabled={saving} className="btn btn-primary" style={{ flex: 1 }}>
                          {saving ? <><div className="spinner" style={{ width: 14, height: 14 }} /> Speichere...</> : <><Save size={16} /> Speichern</>}
                        </button>
                        <button onClick={cancelEdit} disabled={saving} className="btn btn-secondary" style={{ flex: 1 }}>
                          <X size={16} /> Abbrechen
                        </button>
                      </div>
                    </div>
                  </div>
                )}
              </div>
            ))}
          </div>
        </div>
      ))}

      <div style={{
        marginTop: 20,
        padding: 12,
        background: 'var(--surface2)',
        borderRadius: 8,
        fontSize: 12,
        color: 'var(--text3)'
      }}>
        <strong>Hinweis:</strong> Das Fähigkeiten-Mapping (koordinativ, konditionell, etc.) wird in einer späteren Version hinzugefügt.
      </div>
    </div>
  )
}
