import { useState, useEffect, useCallback } from 'react'
import { Link } from 'react-router-dom'
import { Gauge, Plus, Pencil, Trash2, Save, X, ChevronUp, ChevronDown } from 'lucide-react'
import { api } from '../utils/api'
import { VALUE_DATA_TYPE_LABELS } from '../utils/referenceValueMeta'

const VALUE_TYPES = ['integer', 'decimal', 'percentage', 'text', 'enum']

function buildValidationRules(form) {
  const t = form.value_data_type
  if (t === 'integer' || t === 'decimal') {
    const r = { positive_only: !!form.vr_positive_only }
    if (form.vr_min !== '' && !Number.isNaN(Number(form.vr_min))) r.min = Number(form.vr_min)
    if (form.vr_max !== '' && !Number.isNaN(Number(form.vr_max))) r.max = Number(form.vr_max)
    return r
  }
  if (t === 'percentage') {
    const r = { positive_only: !!form.vr_positive_only }
    if (form.vr_min !== '' && !Number.isNaN(Number(form.vr_min))) r.min = Number(form.vr_min)
    if (form.vr_max !== '' && !Number.isNaN(Number(form.vr_max))) r.max = Number(form.vr_max)
    return r
  }
  if (t === 'text') {
    const r = { not_empty: !!form.vr_not_empty }
    if (form.vr_max_length !== '' && !Number.isNaN(parseInt(form.vr_max_length, 10))) {
      r.max_length = parseInt(form.vr_max_length, 10)
    }
    return r
  }
  if (t === 'enum') {
    const parts = form.vr_enum_list.split(',').map((s) => s.trim()).filter(Boolean)
    return { allowed_values: parts }
  }
  return {}
}

const emptyForm = () => ({
  key: '',
  label: '',
  category: '',
  description: '',
  default_unit: '',
  value_data_type: 'decimal',
  vr_min: '',
  vr_max: '',
  vr_positive_only: false,
  vr_max_length: '',
  vr_not_empty: true,
  vr_enum_list: '',
  active: true,
  metadata_json: '{}',
})

export default function AdminReferenceValueTypesPage() {
  const [rows, setRows] = useState([])
  const [loading, setLoading] = useState(true)
  const [reorderBusy, setReorderBusy] = useState(false)
  const [error, setError] = useState(null)
  const [toast, setToast] = useState(null)
  const [editingId, setEditingId] = useState(null)
  const [form, setForm] = useState(emptyForm())
  const [showForm, setShowForm] = useState(false)

  const load = useCallback(async () => {
    setLoading(true)
    setError(null)
    try {
      const data = await api.adminListReferenceValueTypes()
      setRows(Array.isArray(data) ? data : [])
    } catch (e) {
      setError(e.message || 'Laden fehlgeschlagen')
    } finally {
      setLoading(false)
    }
  }, [])

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

  const showToast = (msg) => {
    setToast(msg)
    setTimeout(() => setToast(null), 2500)
  }

  const openCreate = () => {
    setEditingId(null)
    setForm(emptyForm())
    setShowForm(true)
  }

  const openEdit = (r) => {
    const vr = r.validation_rules && typeof r.validation_rules === 'object' ? r.validation_rules : {}
    const allowed = Array.isArray(vr.allowed_values) ? vr.allowed_values.join(', ') : ''
    setEditingId(r.id)
    setForm({
      key: r.key || '',
      label: r.label || '',
      category: r.category || '',
      description: r.description || '',
      default_unit: r.default_unit || '',
      value_data_type: r.value_data_type || 'decimal',
      vr_min: vr.min != null ? String(vr.min) : '',
      vr_max: vr.max != null ? String(vr.max) : '',
      vr_positive_only: !!vr.positive_only,
      vr_max_length: vr.max_length != null ? String(vr.max_length) : '',
      vr_not_empty: vr.not_empty !== false,
      vr_enum_list: allowed,
      active: !!r.active,
      metadata_json: r.metadata && typeof r.metadata === 'object' ? JSON.stringify(r.metadata, null, 2) : '{}',
    })
    setShowForm(true)
  }

  const closeForm = () => {
    setShowForm(false)
    setEditingId(null)
    setForm(emptyForm())
  }

  const handleSave = async () => {
    if (!form.label.trim()) {
      setError('Bitte einen Anzeigenamen (label) angeben.')
      return
    }
    if (!form.default_unit.trim()) {
      setError('Standard-Einheit ist erforderlich (bei Nutzern nicht änderbar).')
      return
    }
    if (form.value_data_type === 'enum' && !form.vr_enum_list.trim()) {
      setError('Bei Datentyp „Auswahl (ENUM)“ bitte erlaubte Werte (kommagetrennt) eintragen.')
      return
    }

    let metadata = {}
    try {
      const mj = form.metadata_json.trim() || '{}'
      metadata = JSON.parse(mj)
      if (metadata === null || typeof metadata !== 'object' || Array.isArray(metadata)) {
        setError('Zusatz-Metadaten müssen ein JSON-Objekt sein.')
        return
      }
    } catch {
      setError('Zusatz-Metadaten: ungültiges JSON.')
      return
    }

    const validation_rules = buildValidationRules(form)

    const payload = {
      label: form.label.trim(),
      category: form.category.trim() || null,
      description: form.description.trim() || null,
      default_unit: form.default_unit.trim(),
      value_data_type: form.value_data_type,
      validation_rules,
      active: !!form.active,
      metadata,
    }

    try {
      setError(null)
      if (editingId) {
        await api.adminUpdateReferenceValueType(editingId, payload)
        showToast('Typ gespeichert')
      } else {
        if (!form.key.trim()) {
          setError('Bitte einen technischen Schlüssel (key) angeben.')
          return
        }
        await api.adminCreateReferenceValueType({
          key: form.key.trim().toLowerCase(),
          ...payload,
        })
        showToast('Typ angelegt')
      }
      closeForm()
      await load()
    } catch (e) {
      setError(e.message || 'Speichern fehlgeschlagen')
    }
  }

  const handleDelete = async (r) => {
    if (
      !confirm(
        `Typ „${r.label}“ (${r.key}) wirklich löschen? Nur möglich, wenn keine Nutzer-Einträge existieren.`,
      )
    ) {
      return
    }
    try {
      setError(null)
      await api.adminDeleteReferenceValueType(r.id)
      showToast('Typ gelöscht')
      await load()
    } catch (e) {
      setError(e.message || 'Löschen fehlgeschlagen')
    }
  }

  const moveRow = async (index, dir) => {
    const j = dir === 'up' ? index - 1 : index + 1
    if (j < 0 || j >= rows.length) return
    setReorderBusy(true)
    setError(null)
    const next = [...rows]
    ;[next[index], next[j]] = [next[j], next[index]]
    try {
      await api.adminReorderReferenceValueTypes(next.map((r) => r.id))
      setRows(next)
    } catch (e) {
      setError(e.message || 'Reihenfolge konnte nicht gespeichert werden')
      await load()
    } finally {
      setReorderBusy(false)
    }
  }

  const plausibilisierungBlock = () => {
    const t = form.value_data_type
    if (t === 'integer' || t === 'decimal' || t === 'percentage') {
      return (
        <>
          <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap' }}>
            <div className="settings-page__field" style={{ flex: '1 1 200px', border: 'none', padding: 0 }}>
              <label className="settings-page__field-label" htmlFor="ref-vr-min">
                Minimum (optional)
              </label>
              <input
                id="ref-vr-min"
                type="number"
                step="any"
                className="form-input"
                value={form.vr_min}
                onChange={(e) => setForm((f) => ({ ...f, vr_min: e.target.value }))}
              />
            </div>
            <div className="settings-page__field" style={{ flex: '1 1 200px', border: 'none', padding: 0 }}>
              <label className="settings-page__field-label" htmlFor="ref-vr-max">
                Maximum (optional){t === 'percentage' ? ' · global max. 100' : ''}
              </label>
              <input
                id="ref-vr-max"
                type="number"
                step="any"
                className="form-input"
                value={form.vr_max}
                onChange={(e) => setForm((f) => ({ ...f, vr_max: e.target.value }))}
              />
            </div>
          </div>
          <div className="settings-page__field" style={{ border: 'none', padding: '8px 0 0' }}>
            <span className="settings-page__field-label">Optionen</span>
            <label
              htmlFor="ref-vr-pos"
              style={{ display: 'flex', alignItems: 'center', gap: 10, cursor: 'pointer', fontSize: 14 }}
            >
              <input
                id="ref-vr-pos"
                type="checkbox"
                checked={form.vr_positive_only}
                onChange={(e) => setForm((f) => ({ ...f, vr_positive_only: e.target.checked }))}
              />
              Nur positive Zahlen (&gt; 0)
            </label>
          </div>
        </>
      )
    }
    if (t === 'text') {
      return (
        <>
          <div className="settings-page__field" style={{ border: 'none', padding: 0 }}>
            <label className="settings-page__field-label" htmlFor="ref-vr-maxlen">
              Max. Zeichenzahl (optional)
            </label>
            <input
              id="ref-vr-maxlen"
              type="number"
              min={1}
              className="form-input"
              value={form.vr_max_length}
              onChange={(e) => setForm((f) => ({ ...f, vr_max_length: e.target.value }))}
            />
          </div>
          <div className="settings-page__field" style={{ border: 'none', padding: '8px 0 0' }}>
            <label htmlFor="ref-vr-ne" style={{ display: 'flex', alignItems: 'center', gap: 10, cursor: 'pointer', fontSize: 14 }}>
              <input
                id="ref-vr-ne"
                type="checkbox"
                checked={form.vr_not_empty}
                onChange={(e) => setForm((f) => ({ ...f, vr_not_empty: e.target.checked }))}
              />
              Nicht leer erlauben
            </label>
          </div>
        </>
      )
    }
    if (t === 'enum') {
      return (
        <div className="settings-page__field" style={{ border: 'none', padding: 0 }}>
          <label className="settings-page__field-label" htmlFor="ref-vr-enum">
            Erlaubte Werte (kommagetrennt)
          </label>
          <textarea
            id="ref-vr-enum"
            className="form-input"
            rows={3}
            value={form.vr_enum_list}
            onChange={(e) => setForm((f) => ({ ...f, vr_enum_list: e.target.value }))}
            placeholder="z. B. niedrig, mittel, hoch"
            spellCheck={false}
          />
        </div>
      )
    }
    return <p style={{ fontSize: 13, color: 'var(--text3)', margin: 0 }}>Keine zusätzlichen Regeln für diesen Typ.</p>
  }

  if (loading) {
    return (
      <div style={{ textAlign: 'center', padding: 48 }}>
        <div className="spinner" />
      </div>
    )
  }

  return (
    <div className="page" style={{ textAlign: 'left' }}>
      <div className="page-header" style={{ marginBottom: 16 }}>
        <h1 style={{ display: 'flex', alignItems: 'center', gap: 10, fontSize: 22, margin: 0 }}>
          <Gauge size={26} color="var(--accent)" />
          Referenz-Kennwerte (Typen)
        </h1>
        <p style={{ fontSize: 13, color: 'var(--text2)', marginTop: 8, lineHeight: 1.6 }}>
          Kategorie, Datentyp und Plausibilisierung steuern die Nutzererfassung. Die Standard-Einheit ist bei der
          Eingabe fix; Prozentwerte liegen grundsätzlich zwischen 0 und 100.
        </p>
        <div style={{ marginTop: 12, display: 'flex', flexWrap: 'wrap', gap: 8 }}>
          <Link to="/admin/g/goals" className="btn btn-secondary" style={{ fontSize: 13 }}>
            ← Zur Gruppe „Ziele & Fokus“
          </Link>
          <button type="button" className="btn btn-primary" onClick={openCreate}>
            <Plus size={16} style={{ marginRight: 6 }} />
            Neuer Typ
          </button>
        </div>
      </div>

      {toast && (
        <div
          style={{
            marginBottom: 12,
            padding: '10px 14px',
            background: 'var(--accent-light)',
            color: 'var(--accent-dark)',
            borderRadius: 8,
            fontSize: 14,
          }}
        >
          {toast}
        </div>
      )}

      {error && (
        <div className="card" style={{ background: '#FEF2F2', border: '1px solid #FCA5A5', marginBottom: 16 }}>
          <p style={{ color: '#DC2626', margin: 0, fontSize: 14 }}>{error}</p>
        </div>
      )}

      {showForm && (
        <div className="card section-gap" style={{ marginBottom: 16 }}>
          <div className="card-title" style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            {editingId ? 'Typ bearbeiten' : 'Neuer Typ'}
            <button type="button" className="btn btn-secondary" onClick={closeForm} style={{ padding: '6px 10px' }}>
              <X size={16} />
            </button>
          </div>
          <div>
            <div className="settings-page__field">
              <label className="settings-page__field-label" htmlFor="ref-admin-key">
                Technischer Schlüssel (key)
              </label>
              <input
                id="ref-admin-key"
                className="form-input"
                disabled={!!editingId}
                value={form.key}
                onChange={(e) => setForm((f) => ({ ...f, key: e.target.value }))}
                placeholder="z. B. max_heart_rate"
                autoComplete="off"
              />
              <p style={{ fontSize: 12, color: 'var(--text3)', margin: '4px 0 0', textAlign: 'left' }}>
                Kleinbuchstaben, Ziffern, Unterstriche; nach Anlage nicht änderbar.
              </p>
            </div>
            <div className="settings-page__field">
              <label className="settings-page__field-label" htmlFor="ref-admin-label">
                Anzeigename
              </label>
              <input
                id="ref-admin-label"
                className="form-input"
                value={form.label}
                onChange={(e) => setForm((f) => ({ ...f, label: e.target.value }))}
                placeholder="z. B. Maximale Herzfrequenz"
              />
            </div>
            <div className="settings-page__field">
              <label className="settings-page__field-label" htmlFor="ref-admin-cat">
                Kategorie (Freitext)
              </label>
              <input
                id="ref-admin-cat"
                className="form-input"
                value={form.category}
                onChange={(e) => setForm((f) => ({ ...f, category: e.target.value }))}
                placeholder="z. B. Herz-Kreislauf"
              />
            </div>
            <div className="settings-page__field">
              <label className="settings-page__field-label" htmlFor="ref-admin-desc">
                Beschreibung
              </label>
              <textarea
                id="ref-admin-desc"
                className="form-input"
                rows={3}
                value={form.description}
                onChange={(e) => setForm((f) => ({ ...f, description: e.target.value }))}
                placeholder="Kurze Erklärung für Nutzer und Admins"
              />
            </div>
            <div className="settings-page__field">
              <label className="settings-page__field-label" htmlFor="ref-admin-vdt">
                Datentyp des Werts
              </label>
              <select
                id="ref-admin-vdt"
                className="form-input"
                value={form.value_data_type}
                onChange={(e) => setForm((f) => ({ ...f, value_data_type: e.target.value }))}
              >
                {VALUE_TYPES.map((k) => (
                  <option key={k} value={k}>
                    {VALUE_DATA_TYPE_LABELS[k] || k}
                  </option>
                ))}
              </select>
            </div>
            <div className="settings-page__field">
              <label className="settings-page__field-label">Plausibilisierung (je Datentyp)</label>
              {plausibilisierungBlock()}
            </div>
            <div className="settings-page__field">
              <label className="settings-page__field-label" htmlFor="ref-admin-unit">
                Standard-Einheit (fix bei Nutzererfassung)
              </label>
              <input
                id="ref-admin-unit"
                className="form-input"
                value={form.default_unit}
                onChange={(e) => setForm((f) => ({ ...f, default_unit: e.target.value }))}
                placeholder="bpm, %, Stufe, …"
              />
            </div>
            <div className="settings-page__field">
              <span className="settings-page__field-label">Sichtbarkeit</span>
              <label
                htmlFor="ref-admin-active"
                style={{
                  display: 'flex',
                  alignItems: 'center',
                  gap: 10,
                  justifyContent: 'flex-start',
                  cursor: 'pointer',
                  fontSize: 14,
                  color: 'var(--text1)',
                  textAlign: 'left',
                }}
              >
                <input
                  id="ref-admin-active"
                  type="checkbox"
                  checked={form.active}
                  onChange={(e) => setForm((f) => ({ ...f, active: e.target.checked }))}
                />
                Aktiv (für Nutzer sichtbar)
              </label>
            </div>
            <div className="settings-page__field" style={{ borderBottom: 'none' }}>
              <label className="settings-page__field-label" htmlFor="ref-admin-meta">
                Zusatz-Metadaten (JSON-Objekt, optional)
              </label>
              <textarea
                id="ref-admin-meta"
                className="form-input"
                rows={4}
                value={form.metadata_json}
                onChange={(e) => setForm((f) => ({ ...f, metadata_json: e.target.value }))}
                placeholder="{}"
                spellCheck={false}
              />
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginTop: 8 }}>
              <button type="button" className="btn btn-primary btn-full" onClick={handleSave}>
                <Save size={16} style={{ marginRight: 6 }} />
                Speichern
              </button>
              <button type="button" className="btn btn-secondary btn-full" onClick={closeForm}>
                Abbrechen
              </button>
            </div>
          </div>
        </div>
      )}

      <div className="card">
        <div className="card-title">Alle Typen ({rows.length})</div>
        <p style={{ fontSize: 13, color: 'var(--text2)', marginTop: 0, marginBottom: 12, lineHeight: 1.5 }}>
          Reihenfolge in der Liste und in den Nutzer-Dropdowns: Zeile mit <strong>hoch/runter</strong> verschieben.
        </p>
        <div style={{ overflowX: 'auto' }}>
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 14 }}>
            <thead>
              <tr style={{ textAlign: 'left', borderBottom: '1px solid var(--border)', color: 'var(--text2)' }}>
                <th style={{ padding: '8px 4px', width: 44 }} aria-label="Reihenfolge" title="Reihenfolge" />
                <th style={{ padding: '8px 6px' }}>Key</th>
                <th style={{ padding: '8px 6px' }}>Name</th>
                <th style={{ padding: '8px 6px' }}>Kategorie</th>
                <th style={{ padding: '8px 6px' }}>Typ</th>
                <th style={{ padding: '8px 6px' }}>Einheit</th>
                <th style={{ padding: '8px 6px' }}>Aktiv</th>
                <th style={{ padding: '8px 6px' }} />
              </tr>
            </thead>
            <tbody>
              {rows.map((r, i) => (
                <tr key={r.id} style={{ borderBottom: '1px solid var(--border)' }}>
                  <td style={{ padding: '6px 4px', verticalAlign: 'middle' }}>
                    <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
                      <button
                        type="button"
                        className="btn btn-secondary"
                        style={{ padding: '4px 6px', minHeight: 0, lineHeight: 1 }}
                        disabled={reorderBusy || i === 0}
                        title="Nach oben"
                        onClick={() => moveRow(i, 'up')}
                        aria-label="Nach oben"
                      >
                        <ChevronUp size={16} />
                      </button>
                      <button
                        type="button"
                        className="btn btn-secondary"
                        style={{ padding: '4px 6px', minHeight: 0, lineHeight: 1 }}
                        disabled={reorderBusy || i === rows.length - 1}
                        title="Nach unten"
                        onClick={() => moveRow(i, 'down')}
                        aria-label="Nach unten"
                      >
                        <ChevronDown size={16} />
                      </button>
                    </div>
                  </td>
                  <td style={{ padding: '10px 6px', fontFamily: 'monospace', fontSize: 13 }}>{r.key}</td>
                  <td style={{ padding: '10px 6px' }}>{r.label}</td>
                  <td style={{ padding: '10px 6px', color: 'var(--text2)' }}>{r.category || '–'}</td>
                  <td style={{ padding: '10px 6px' }}>
                    {VALUE_DATA_TYPE_LABELS[r.value_data_type] || r.value_data_type || '–'}
                  </td>
                  <td style={{ padding: '10px 6px', color: 'var(--text2)' }}>{r.default_unit || '–'}</td>
                  <td style={{ padding: '10px 6px' }}>{r.active ? '✓' : '–'}</td>
                  <td style={{ padding: '6px', textAlign: 'right', whiteSpace: 'nowrap' }}>
                    <button
                      type="button"
                      className="btn btn-secondary"
                      style={{ padding: '6px 10px', marginRight: 6 }}
                      onClick={() => openEdit(r)}
                      title="Bearbeiten"
                    >
                      <Pencil size={14} />
                    </button>
                    <button
                      type="button"
                      className="btn btn-secondary"
                      style={{ padding: '6px 10px', color: 'var(--danger)' }}
                      onClick={() => handleDelete(r)}
                      title="Löschen"
                    >
                      <Trash2 size={14} />
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        {rows.length === 0 && (
          <p style={{ color: 'var(--text2)', margin: 0, fontSize: 14 }}>Noch keine Typen – „Neuer Typ“ anlegen.</p>
        )}
      </div>
    </div>
  )
}
