import { useEffect, useMemo, useState } from 'react'
import { ChevronDown, ChevronUp } from 'lucide-react'
import { api } from '../utils/api'
import { KPI_KCAL_WINDOW_DEFAULT } from './bodyChartDays'
import { KPI_TILE_AVG_KCAL, KPI_TILE_BODY_FAT, REF_TILE_PREFIX } from './kpiBoardTiles'

/**
 * @param {{ tiles: { id: string }[] | undefined, onChange: (next: { id: string }[] | undefined) => void }} props
 * undefined tiles = automatisch (kein config.tiles)
 */
export default function KpiBoardConfigEditor({ tiles, onChange }) {
  const [catalog, setCatalog] = useState([])

  useEffect(() => {
    let ok = true
    api
      .listProfileReferenceValuesSummary()
      .then((s) => {
        if (!ok) return
        /** @type {{ id: string, label: string }[]} */
        const opts = [
          { id: KPI_TILE_BODY_FAT, label: 'Körperfett (Caliper)' },
          { id: KPI_TILE_AVG_KCAL, label: `Ø Kalorien (${KPI_KCAL_WINDOW_DEFAULT} Tage)` },
        ]
        const list = Array.isArray(s?.tiles) ? s.tiles : []
        for (const t of list) {
          if (t?.type_key) {
            opts.push({
              id: `${REF_TILE_PREFIX}${t.type_key}`,
              label: t.type_label || t.type_key,
            })
          }
        }
        setCatalog(opts)
      })
      .catch(() => {
        if (ok) setCatalog([])
      })
    return () => {
      ok = false
    }
  }, [])

  const labelById = useMemo(() => Object.fromEntries(catalog.map((c) => [c.id, c.label])), [catalog])

  const ordered = Array.isArray(tiles) ? tiles : []

  const toggle = (id, checked) => {
    if (checked) {
      if (ordered.some((t) => t.id === id) || ordered.length >= 9) return
      onChange([...ordered, { id }])
    } else {
      const next = ordered.filter((t) => t.id !== id)
      onChange(next.length ? next : [])
    }
  }

  const move = (index, delta) => {
    const j = index + delta
    if (j < 0 || j >= ordered.length) return
    const next = [...ordered]
    const tmp = next[index]
    next[index] = next[j]
    next[j] = tmp
    onChange(next)
  }

  return (
    <div style={{ marginTop: 10, marginLeft: 28 }}>
      <div style={{ fontSize: 12, color: 'var(--text2)', marginBottom: 8, lineHeight: 1.5 }}>
        <strong>KPI-Kacheln:</strong> wählen und sortieren (max. 9). Ohne Auswahl oder „Automatisch“ =
        bisherige automatische Belegung.
      </div>
      <button
        type="button"
        className="btn btn-secondary"
        style={{ marginBottom: 10, fontSize: 12, padding: '6px 12px' }}
        onClick={() => onChange(undefined)}
      >
        Automatisch (wie bisher)
      </button>
      {ordered.length > 0 && (
        <div style={{ marginBottom: 12 }}>
          <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--text3)', marginBottom: 6 }}>
            Reihenfolge (oben zuerst)
          </div>
          <ul style={{ listStyle: 'none', padding: 0, margin: 0 }}>
            {ordered.map((t, idx) => (
              <li
                key={`${t.id}-${idx}`}
                style={{
                  display: 'flex',
                  alignItems: 'center',
                  gap: 8,
                  padding: '6px 0',
                  borderBottom: '1px solid var(--border)',
                  fontSize: 13,
                }}
              >
                <span style={{ flex: 1 }}>{labelById[t.id] || t.id}</span>
                <button
                  type="button"
                  className="btn btn-secondary"
                  style={{ padding: '4px 8px' }}
                  aria-label="Nach oben"
                  onClick={() => move(idx, -1)}
                >
                  <ChevronUp size={16} />
                </button>
                <button
                  type="button"
                  className="btn btn-secondary"
                  style={{ padding: '4px 8px' }}
                  aria-label="Nach unten"
                  onClick={() => move(idx, 1)}
                >
                  <ChevronDown size={16} />
                </button>
              </li>
            ))}
          </ul>
        </div>
      )}
      <div
        style={{
          display: 'grid',
          gridTemplateColumns: 'repeat(auto-fill, minmax(220px, 1fr))',
          gap: 8,
          maxHeight: 220,
          overflowY: 'auto',
          padding: 8,
          background: 'var(--surface)',
          borderRadius: 8,
          border: '1px solid var(--border)',
        }}
      >
        {catalog.map((c) => (
          <label
            key={c.id}
            style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 12, cursor: 'pointer' }}
          >
            <input
              type="checkbox"
              checked={ordered.some((t) => t.id === c.id)}
              onChange={(e) => toggle(c.id, e.target.checked)}
            />
            <span>{c.label}</span>
          </label>
        ))}
      </div>
    </div>
  )
}
