import React from 'react'

interface Section<K extends string> {
  key: K
  label: string
  disabled?: boolean
  tag?: string
}

interface SectionRailProps<K extends string> {
  sections: Section<K>[]
  active: K
  onSelect: (k: K) => void
}

export function SectionRail<K extends string>({
  sections,
  active,
  onSelect,
}: SectionRailProps<K>): React.JSX.Element {
  return (
    <div className="section-rail">
      {sections.map((s) => {
        const isActive = s.key === active
        const cls = [
          'section-row',
          isActive ? 'active' : '',
          s.disabled ? 'disabled' : '',
        ]
          .filter(Boolean)
          .join(' ')

        return (
          <div
            key={s.key}
            className={cls}
            onClick={s.disabled ? undefined : () => onSelect(s.key)}
            role={s.disabled ? undefined : 'button'}
            tabIndex={s.disabled ? undefined : 0}
            onKeyDown={
              s.disabled
                ? undefined
                : (e) => {
                    if (e.key === 'Enter' || e.key === ' ') onSelect(s.key)
                  }
            }
          >
            {s.label}
            {s.tag != null && (
              <span className="section-row-tag">{s.tag}</span>
            )}
          </div>
        )
      })}
    </div>
  )
}
