import React, { useEffect, useState } from 'react'
import { useAuth } from '../../context/AuthContext'
import api from '../../utils/api'

export default function MaturityModelsAdminPanel() {
  const { user } = useAuth()
  const isSuperadmin = user?.role === 'superadmin'

  const [models, setModels] = useState([])
  const [selectedId, setSelectedId] = useState(null)
  const [detail, setDetail] = useState(null)
  const [loading, setLoading] = useState(false)
  const [saving, setSaving] = useState(false)
  const [error, setError] = useState('')
  const [allSkills, setAllSkills] = useState([])

  const [newModel, setNewModel] = useState({
    name: '',
    level_count: 5,
    status: 'draft'
  })

  const [meta, setMeta] = useState(null)
  const [levelCount, setLevelCount] = useState(5)
  const [levelsForm, setLevelsForm] = useState([])
  const [cellDraft, setCellDraft] = useState({})
  const [skillToAdd, setSkillToAdd] = useState('')

  useEffect(() => {
    let cancelled = false
    ;(async () => {
      try {
        const [m, sk] = await Promise.all([
          api.listMaturityModels({}),
          api.listSkills({ status: 'active' })
        ])
        if (!cancelled) {
          setModels(m)
          setAllSkills(sk)
        }
      } catch (e) {
        if (!cancelled) setError(e.message)
      }
    })()
    return () => { cancelled = true }
  }, [])

  async function refreshModels() {
    const m = await api.listMaturityModels({})
    setModels(m)
  }

  async function selectModel(id) {
    setSelectedId(id)
    setLoading(true)
    setError('')
    try {
      const d = await api.getMaturityModel(id)
      setDetail(d)
      setMeta({
        name: d.name,
        description: d.description || '',
        status: d.status,
        version: d.version || '1.0'
      })
      const lc = parseInt(String(d.level_count), 10)
      setLevelCount(lc)
      setLevelsForm(
        (d.levels || []).map((l) => ({
          level_number: l.level_number,
          name: l.name,
          description: l.description || '',
          sort_order: l.sort_order
        }))
      )
      const draft = {}
      for (const r of d.skill_levels || []) {
        draft[`${r.skill_id}-${r.level_number}`] = {
          description: r.description || '',
          observable_criteria: r.observable_criteria || ''
        }
      }
      setCellDraft(draft)
    } catch (e) {
      setError(e.message)
      setDetail(null)
      setMeta(null)
    } finally {
      setLoading(false)
    }
  }

  async function handleCreate(e) {
    e.preventDefault()
    setError('')
    setSaving(true)
    try {
      const payload = {
        name: newModel.name.trim(),
        level_count: parseInt(String(newModel.level_count), 10),
        status: newModel.status
      }
      const created = await api.createMaturityModel(payload)
      await refreshModels()
      await selectModel(created.id)
      setNewModel({
        name: '',
        level_count: 5,
        status: 'draft'
      })
    } catch (e) {
      setError(e.message)
    } finally {
      setSaving(false)
    }
  }

  async function handleSaveMeta() {
    if (!selectedId || !meta) return
    setError('')
    setSaving(true)
    try {
      await api.updateMaturityModel(selectedId, {
        name: meta.name,
        description: meta.description || null,
        status: meta.status,
        version: meta.version
      })
      await refreshModels()
      await selectModel(selectedId)
    } catch (e) {
      setError(e.message)
    } finally {
      setSaving(false)
    }
  }

  async function handleSaveLevels() {
    if (!selectedId || !meta) return
    setError('')
    setSaving(true)
    try {
      await api.updateMaturityModel(selectedId, {
        level_count: parseInt(String(levelCount), 10),
        levels: levelsForm.map((l) => ({
          level_number: parseInt(String(l.level_number), 10),
          name: l.name,
          description: l.description || null,
          sort_order: parseInt(String(l.sort_order), 10)
        }))
      })
      await refreshModels()
      await selectModel(selectedId)
    } catch (e) {
      setError(e.message)
    } finally {
      setSaving(false)
    }
  }

  async function handleSaveMatrix() {
    if (!selectedId || !detail) return
    if (!detail.model_skills?.length) {
      setError('Matrix: Zuerst Fähigkeiten hinzufügen.')
      return
    }
    setError('')
    setSaving(true)
    try {
      const entries = []
      for (const ms of detail.model_skills) {
        for (const lev of detail.levels || []) {
          const key = `${ms.skill_id}-${lev.level_number}`
          const d = cellDraft[key] || { description: '', observable_criteria: '' }
          entries.push({
            skill_id: ms.skill_id,
            level_number: lev.level_number,
            description: (d.description || '').trim(),
            observable_criteria: (d.observable_criteria || '').trim() || null
          })
        }
      }
      await api.upsertMaturityModelSkillLevels(selectedId, { entries })
      await selectModel(selectedId)
    } catch (e) {
      setError(e.message)
    } finally {
      setSaving(false)
    }
  }

  async function handleAddSkill() {
    if (!selectedId || !skillToAdd) return
    setError('')
    setSaving(true)
    try {
      await api.addMaturityModelSkill(selectedId, { skill_id: parseInt(String(skillToAdd), 10) })
      setSkillToAdd('')
      await selectModel(selectedId)
    } catch (e) {
      setError(e.message)
    } finally {
      setSaving(false)
    }
  }

  async function handleRemoveSkill(skillId) {
    if (!selectedId) return
    if (!confirm('Fähigkeit aus dem Modell entfernen? Zelltexte werden gelöscht.')) return
    setError('')
    setSaving(true)
    try {
      await api.removeMaturityModelSkill(selectedId, skillId)
      await selectModel(selectedId)
    } catch (e) {
      setError(e.message)
    } finally {
      setSaving(false)
    }
  }

  async function handleDeleteModel() {
    if (!selectedId || !isSuperadmin) return
    if (!confirm('Reifegradmodell dauerhaft löschen?')) return
    setError('')
    setSaving(true)
    try {
      await api.deleteMaturityModel(selectedId)
      setSelectedId(null)
      setDetail(null)
      setMeta(null)
      await refreshModels()
    } catch (e) {
      setError(e.message)
    } finally {
      setSaving(false)
    }
  }

  function onLevelCountChange(raw) {
    const next = Math.max(3, Math.min(10, parseInt(String(raw), 10) || 3))
    setLevelCount(next)
    setLevelsForm((prev) => {
      const byNum = Object.fromEntries(prev.map((r) => [r.level_number, { ...r }]))
      const rows = []
      for (let i = 1; i <= next; i++) {
        rows.push(
          byNum[i] || {
            level_number: i,
            name: `Stufe ${i}`,
            description: '',
            sort_order: i
          }
        )
      }
      return rows
    })
  }

  function setCell(skillId, levelNumber, field, value) {
    const key = `${skillId}-${levelNumber}`
    setCellDraft((prev) => ({
      ...prev,
      [key]: {
        description: field === 'description' ? value : (prev[key]?.description ?? ''),
        observable_criteria:
          field === 'observable_criteria' ? value : (prev[key]?.observable_criteria ?? '')
      }
    }))
  }

  return (
    <div className="admin-matrix-panel">
      <p className="admin-matrix-panel__intro muted">
        Ablauf: Modell wählen → Stammdaten → Stufen definieren → Fähigkeiten zuordnen → Matrix-Zelltexte pflegen.
        Fähigkeiten legen Sie im Tab „Katalog und Hierarchie“ an.{' '}
        <strong>Zuordnung zu Fokusbereich / Stil / Zielgruppe</strong> ist hier vorerst deaktiviert; bestehende
        Einträge in der Datenbank bleiben unverändert, bis wir das Konzept (Überschneidungen) geklärt haben.
      </p>

      {error ? (
        <div className="card admin-matrix-alert" role="alert">
          {error}
        </div>
      ) : null}

      <div className="admin-matrix-layout">
        <aside className="admin-matrix-sidebar card">
          <h2 className="admin-matrix-sidebar__title">Reifegradmodelle</h2>
          <ul className="admin-matrix-model-list">
            {models.map((m) => (
              <li key={m.id}>
                <button
                  type="button"
                  className={
                    'admin-matrix-model-btn' +
                    (selectedId === m.id ? ' admin-matrix-model-btn--active' : '')
                  }
                  onClick={() => selectModel(m.id)}
                >
                  <span className="admin-matrix-model-btn__name">{m.name}</span>
                  <span className="admin-matrix-model-btn__meta muted">
                    {m.status} · {m.level_count} Stufen
                  </span>
                </button>
              </li>
            ))}
          </ul>

          <hr className="admin-matrix-divider" />

          <h3 className="admin-matrix-sidebar__subtitle">Neues Modell</h3>
          <form className="admin-matrix-new-form" onSubmit={handleCreate}>
            <label className="form-label">Name</label>
            <input
              className="form-input"
              value={newModel.name}
              onChange={(e) => setNewModel((s) => ({ ...s, name: e.target.value }))}
              required
            />
            <label className="form-label">Stufenanzahl (3–10)</label>
            <input
              className="form-input"
              type="number"
              min={3}
              max={10}
              inputMode="numeric"
              value={newModel.level_count}
              onChange={(e) => setNewModel((s) => ({ ...s, level_count: e.target.value }))}
            />
            <label className="form-label">Status</label>
            <select
              className="form-input"
              value={newModel.status}
              onChange={(e) => setNewModel((s) => ({ ...s, status: e.target.value }))}
            >
              <option value="draft">Entwurf</option>
              <option value="active">Aktiv</option>
              <option value="archived">Archiviert</option>
            </select>
            <button type="submit" className="btn btn-primary btn-full" disabled={saving}>
              Anlegen
            </button>
          </form>
        </aside>

        <div className="admin-matrix-main">
          {loading ? (
            <div className="admin-matrix-loading" aria-busy="true">
              <div className="spinner" />
              <span className="muted">Lade Modell…</span>
            </div>
          ) : null}

          {!loading && !detail && (
            <div className="card admin-matrix-empty">
              Modell in der linken Spalte wählen oder neu anlegen.
            </div>
          )}

          {!loading && detail && meta && (
            <>
              <section className="card admin-matrix-section">
                <div className="admin-matrix-section__head">
                  <span className="admin-matrix-step">1</span>
                  <h2 className="admin-matrix-section__title">Stammdaten</h2>
                </div>
                <div className="admin-matrix-meta-grid">
                  <div>
                    <label className="form-label">Name</label>
                    <input
                      className="form-input"
                      value={meta.name}
                      onChange={(e) => setMeta((m) => ({ ...m, name: e.target.value }))}
                    />
                  </div>
                  <div>
                    <label className="form-label">Beschreibung</label>
                    <textarea
                      className="form-input"
                      rows={2}
                      value={meta.description}
                      onChange={(e) => setMeta((m) => ({ ...m, description: e.target.value }))}
                    />
                  </div>
                  <div className="admin-matrix-meta-grid__row2">
                    <div>
                      <label className="form-label">Status</label>
                      <select
                        className="form-input"
                        value={meta.status}
                        onChange={(e) => setMeta((m) => ({ ...m, status: e.target.value }))}
                      >
                        <option value="draft">Entwurf</option>
                        <option value="active">Aktiv</option>
                        <option value="archived">Archiviert</option>
                      </select>
                    </div>
                    <div>
                      <label className="form-label">Version</label>
                      <input
                        className="form-input"
                        value={meta.version}
                        onChange={(e) => setMeta((m) => ({ ...m, version: e.target.value }))}
                      />
                    </div>
                  </div>
                </div>
                {((detail.focus_areas || []).length > 0 ||
                  (detail.style_directions || []).length > 0 ||
                  (detail.target_groups || []).length > 0) && (
                  <div className="admin-matrix-context-readonly muted">
                    <strong>Hinweis (nur Anzeige):</strong> In der Datenbank sind noch Kontext-Zuordnungen
                    hinterlegt (Fokus / Stil / Zielgruppe). Diese können Sie hier derzeit nicht ändern.
                    {(detail.focus_areas || []).length ? (
                      <div>Fokusbereiche: {(detail.focus_areas || []).map((f) => f.name).join(', ')}</div>
                    ) : null}
                    {(detail.style_directions || []).length ? (
                      <div>Stilrichtungen: {(detail.style_directions || []).map((s) => s.name).join(', ')}</div>
                    ) : null}
                    {(detail.target_groups || []).length ? (
                      <div>Zielgruppen: {(detail.target_groups || []).map((t) => t.name).join(', ')}</div>
                    ) : null}
                  </div>
                )}
                <div className="admin-matrix-actions">
                  <button type="button" className="btn btn-primary" onClick={handleSaveMeta} disabled={saving}>
                    Stammdaten speichern
                  </button>
                  {isSuperadmin ? (
                    <button type="button" className="btn btn-secondary" onClick={handleDeleteModel} disabled={saving}>
                      Modell löschen
                    </button>
                  ) : null}
                </div>
              </section>

              <section className="card admin-matrix-section">
                <div className="admin-matrix-section__head">
                  <span className="admin-matrix-step">2</span>
                  <h2 className="admin-matrix-section__title">Stufen (Bezeichnungen)</h2>
                </div>
                <p className="admin-matrix-hint muted">
                  Nummern 1…N lückenlos. Stufenanzahl ändert die Matrix; danach „Stufen speichern“.
                </p>
                <div className="admin-matrix-level-count">
                  <label className="form-label">Stufenanzahl (3–10)</label>
                  <input
                    className="form-input"
                    type="number"
                    min={3}
                    max={10}
                    inputMode="numeric"
                    value={levelCount}
                    onChange={(e) => onLevelCountChange(e.target.value)}
                  />
                </div>
                <div className="admin-matrix-table-wrap">
                  <table className="admin-matrix-table admin-matrix-table--levels">
                    <thead>
                      <tr>
                        <th>Nr.</th>
                        <th>Name</th>
                        <th>Beschreibung</th>
                        <th>Sort</th>
                      </tr>
                    </thead>
                    <tbody>
                      {levelsForm.map((row, idx) => (
                        <tr key={row.level_number}>
                          <td>{row.level_number}</td>
                          <td>
                            <input
                              className="form-input"
                              value={row.name}
                              onChange={(e) => {
                                const next = [...levelsForm]
                                next[idx] = { ...row, name: e.target.value }
                                setLevelsForm(next)
                              }}
                            />
                          </td>
                          <td>
                            <input
                              className="form-input"
                              value={row.description}
                              onChange={(e) => {
                                const next = [...levelsForm]
                                next[idx] = { ...row, description: e.target.value }
                                setLevelsForm(next)
                              }}
                            />
                          </td>
                          <td className="admin-matrix-table__narrow">
                            <input
                              className="form-input"
                              type="number"
                              inputMode="numeric"
                              value={row.sort_order}
                              onChange={(e) => {
                                const next = [...levelsForm]
                                next[idx] = { ...row, sort_order: e.target.value }
                                setLevelsForm(next)
                              }}
                            />
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
                <button
                  type="button"
                  className="btn btn-secondary admin-matrix-actions--mt"
                  onClick={handleSaveLevels}
                  disabled={saving}
                >
                  Stufen speichern
                </button>
              </section>

              <section className="card admin-matrix-section">
                <div className="admin-matrix-section__head">
                  <span className="admin-matrix-step">3</span>
                  <h2 className="admin-matrix-section__title">Fähigkeiten im Modell</h2>
                </div>
                <div className="admin-matrix-skill-add">
                  <div className="admin-matrix-skill-add__select">
                    <label className="form-label">Fähigkeit hinzufügen</label>
                    <select
                      className="form-input"
                      value={skillToAdd}
                      onChange={(e) => setSkillToAdd(e.target.value)}
                    >
                      <option value="">— wählen —</option>
                      {allSkills.map((s) => (
                        <option key={s.id} value={s.id}>{s.name}</option>
                      ))}
                    </select>
                  </div>
                  <button
                    type="button"
                    className="btn btn-primary admin-matrix-skill-add__btn"
                    onClick={handleAddSkill}
                    disabled={saving || !skillToAdd}
                  >
                    Hinzufügen
                  </button>
                </div>
                <ul className="admin-matrix-skill-list">
                  {(detail.model_skills || []).map((ms) => (
                    <li key={ms.skill_id} className="admin-matrix-skill-list__item">
                      <div className="admin-matrix-skill-list__row">
                        <strong className="admin-matrix-skill-list__name">{ms.skill_name}</strong>
                        <button
                          type="button"
                          className="btn btn-secondary btn-small"
                          onClick={() => handleRemoveSkill(ms.skill_id)}
                        >
                          Entfernen
                        </button>
                      </div>
                      {(ms.skill_main_category_name || ms.skill_subcategory_name) ? (
                        <div className="admin-matrix-skill-list__path muted">
                          {ms.skill_main_category_name}
                          {ms.skill_subcategory_name ? ` › ${ms.skill_subcategory_name}` : ''}
                        </div>
                      ) : null}
                    </li>
                  ))}
                </ul>
              </section>

              <section className="card admin-matrix-section">
                <div className="admin-matrix-section__head">
                  <span className="admin-matrix-step">4</span>
                  <h2 className="admin-matrix-section__title">Matrix (Zielbild je Stufe)</h2>
                </div>
                <p className="admin-matrix-hint muted">
                  Leere Zellen werden beim Speichern entfernt. Unten: Beobachtungskriterien (optional).
                </p>
                <div className="admin-matrix-matrix-scroll">
                  <table className="admin-matrix-table admin-matrix-table--matrix">
                    <thead>
                      <tr>
                        <th className="admin-matrix-matrix__corner">Fähigkeit</th>
                        {(detail.levels || []).map((l) => (
                          <th key={l.level_number} className="admin-matrix-matrix__level-head">
                            {l.level_number}. {l.name}
                          </th>
                        ))}
                      </tr>
                    </thead>
                    <tbody>
                      {(detail.model_skills || []).map((ms) => (
                        <tr key={ms.skill_id}>
                          <td className="admin-matrix-matrix__skill-cell">
                            <div>{ms.skill_name}</div>
                            {(ms.skill_main_category_name || ms.skill_subcategory_name) ? (
                              <div className="admin-matrix-matrix__skill-path muted">
                                {ms.skill_main_category_name || '—'}
                                {ms.skill_subcategory_name ? ` › ${ms.skill_subcategory_name}` : ''}
                              </div>
                            ) : null}
                          </td>
                          {(detail.levels || []).map((l) => {
                            const key = `${ms.skill_id}-${l.level_number}`
                            const d = cellDraft[key] || { description: '', observable_criteria: '' }
                            return (
                              <td key={l.level_number} className="admin-matrix-matrix__cell">
                                <textarea
                                  className="form-input admin-matrix-matrix__ta"
                                  rows={3}
                                  placeholder="Zielbild / Erwartung"
                                  value={d.description}
                                  onChange={(e) => setCell(ms.skill_id, l.level_number, 'description', e.target.value)}
                                />
                                <textarea
                                  className="form-input admin-matrix-matrix__ta admin-matrix-matrix__ta--criteria"
                                  rows={2}
                                  placeholder="Beobachtungskriterien (optional)"
                                  value={d.observable_criteria}
                                  onChange={(e) => setCell(ms.skill_id, l.level_number, 'observable_criteria', e.target.value)}
                                />
                              </td>
                            )
                          })}
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
                <button
                  type="button"
                  className="btn btn-primary admin-matrix-actions--mt"
                  onClick={handleSaveMatrix}
                  disabled={saving || !(detail.model_skills || []).length}
                >
                  Matrix speichern
                </button>
              </section>
            </>
          )}
        </div>
      </div>
    </div>
  )
}

