import React, { useCallback } from 'react'

interface SkillLevelBarProps {
  value: number | ''
  onChange: (value: number) => void
  min?: number
  max?: number
  disabled?: boolean
  showHelp?: boolean
}

function segmentColor(i: number) {
  // Use darker, more contrast-friendly shades in dark mode
  if (i <= 3) return 'bg-red-500 hover:bg-red-600 dark:bg-red-700 dark:hover:bg-red-600'
  if (i <= 6) return 'bg-green-500 hover:bg-green-600 dark:bg-green-700 dark:hover:bg-green-600'
  return 'bg-purple-500 hover:bg-purple-600 dark:bg-purple-700 dark:hover:bg-purple-600'
}

export default function SkillLevelBar({ value, onChange, min = 1, max = 10, disabled = false, showHelp = true }: SkillLevelBarProps) {
  const handleKey = useCallback((e: React.KeyboardEvent<HTMLDivElement>) => {
    if (disabled) return
    if (e.key === 'ArrowRight' || e.key === 'ArrowUp') {
      e.preventDefault()
      const v = typeof value === 'number' ? value : min - 1
      onChange(Math.min(max, v + 1))
    } else if (e.key === 'ArrowLeft' || e.key === 'ArrowDown') {
      e.preventDefault()
      const v = typeof value === 'number' ? value : min
      onChange(Math.max(min, v - 1))
    } else if (e.key === 'Home') {
      e.preventDefault(); onChange(min)
    } else if (e.key === 'End') {
      e.preventDefault(); onChange(max)
    }
  }, [value, onChange, min, max, disabled])

  const current = typeof value === 'number' ? value : 0

  return (
    <div className="space-y-2">
      <div
        className={`flex items-center gap-1 select-none ${disabled ? 'opacity-60' : ''}`}
        role="slider"
        aria-valuemin={min}
        aria-valuemax={max}
        aria-valuenow={current || undefined}
        tabIndex={disabled ? -1 : 0}
        onKeyDown={handleKey}
      >
        {Array.from({ length: max }, (_, idx) => idx + 1).map(i => {
          const active = i <= current
          return (
            <button
              key={i}
              type="button"
              className={`h-6 flex-1 rounded-sm transition-colors ${
                active
                  ? segmentColor(i)
                  : 'bg-border-default hover:bg-bg-gray dark:bg-dark-border/40 dark:hover:bg-dark-border/60'
              } ${disabled ? 'cursor-not-allowed' : 'cursor-pointer'}`}
              aria-label={`Level ${i}`}
              onClick={() => !disabled && onChange(i)}
            />
          )
        })}
        <span className="ml-3 text-small text-secondary min-w-[2ch] text-right">{current || ''}</span>
      </div>
      {showHelp && (
        <div className="text-small text-tertiary">
          <span className="mr-4"><strong>1</strong> Anfänger</span>
          <span className="mr-4"><strong>5</strong> Fortgeschritten</span>
          <span><strong>10</strong> Experte</span>
        </div>
      )}
    </div>
  )
}
