import { Link, useLocation, useNavigate } from 'react-router-dom'
import { useAuth } from '../context/AuthContext'
import { useState, useEffect } from 'react'
import { api } from '../api/client'
import { PRIMARY_NAV, visibleFor, hasAnySettings } from './navConfig'

interface KioskHealthDevice {
  status: 'pending' | 'approved' | 'revoked'
  heartbeat_status: 'online' | 'stale' | 'offline'
}

const ROLE_LABELS: Record<string, string> = {
  SUPER_ADMIN:   'Super Admin',
  COMPANY_ADMIN: 'Administrator',
  HR:            'HR',
  MANAGER:       'Manager',
  EMPLOYEE:      'Mitarbeiter',
}

const KIOSK_HEALTH_ROLES = ['COMPANY_ADMIN', 'SUPER_ADMIN']

function KioskHealthBadge({ userRole }: { userRole: string }) {
  const navigate = useNavigate()
  const [online, setOnline] = useState(0)
  const [total, setTotal]   = useState(0)
  const [visible, setVisible] = useState(false)

  async function fetchHealth() {
    try {
      const devices = await api.get<KioskHealthDevice[]>('/kiosk/devices')
      const approved = devices.filter(d => d.status === 'approved')
      const onlineCount = approved.filter(d => d.heartbeat_status === 'online').length
      setTotal(approved.length)
      setOnline(onlineCount)
      setVisible(true)
    } catch {
      setVisible(false)
    }
  }

  useEffect(() => {
    if (!KIOSK_HEALTH_ROLES.includes(userRole)) return
    fetchHealth()
    const interval = setInterval(fetchHealth, 30000)
    return () => clearInterval(interval)
  }, [userRole])

  if (!KIOSK_HEALTH_ROLES.includes(userRole) || !visible || total === 0) return null

  let dotColor = 'bg-green-500'
  let textColor = 'text-green-700'
  let bgColor = 'bg-green-50 border-green-200'

  if (online === 0) {
    dotColor = 'bg-red-500'
    textColor = 'text-red-700'
    bgColor = 'bg-red-50 border-red-200'
  } else if (online < total) {
    dotColor = 'bg-yellow-400'
    textColor = 'text-yellow-700'
    bgColor = 'bg-yellow-50 border-yellow-200'
  }

  return (
    <button
      onClick={() => navigate('/settings/kiosk')}
      title='Kiosk-Geräte-Status – klicken zum Öffnen'
      className={`flex items-center gap-1.5 text-xs px-2 py-1 rounded-full border font-medium transition-opacity hover:opacity-80 ${bgColor} ${textColor}`}
    >
      <span className={`w-2 h-2 rounded-full flex-shrink-0 ${dotColor}`} />
      {online}/{total} Kiosks
    </button>
  )
}

export function Layout({ children, userRole, userName }: {
  children: React.ReactNode
  userRole: string
  userName: string
}) {
  const { logout } = useAuth()
  const { pathname } = useLocation()

  const visiblePrimary = visibleFor(PRIMARY_NAV, userRole)
  const settingsActive = pathname.startsWith('/settings') ||
    ['/work-schedules', '/users/import', '/users', '/hr/special-assignments',
     '/hr/payouts', '/admin/tenants'].includes(pathname)
  const showSettings   = hasAnySettings(userRole)

  const initials = userName
    ? userName.split(' ').map(w => w[0]).join('').slice(0, 2).toUpperCase()
    : '?'

  return (
    <div className='min-h-screen bg-gray-50'>
      <header className='bg-white border-b border-gray-200 sticky top-0 z-30'>
        <div className='max-w-7xl mx-auto px-4 sm:px-6 h-14 flex items-center justify-between gap-2'>

          {/* Logo */}
          <Link to='/dashboard' className='flex items-center gap-2 flex-shrink-0'>
            <div className='w-8 h-8 bg-blue-600 rounded-lg flex items-center justify-center'>
              <span className='text-white font-bold text-sm'>TM</span>
            </div>
            <span className='font-bold text-gray-800 hidden lg:block text-sm'>TimeMaster</span>
          </Link>

          {/* Hauptnavigation */}
          <nav className='flex items-center gap-0.5 flex-1 overflow-x-auto'>
            {visiblePrimary.map(n => (
              <Link
                key={n.path}
                to={n.path}
                className={`px-3 py-2 rounded-lg text-sm font-medium transition-colors whitespace-nowrap ${
                  pathname === n.path
                    ? 'bg-blue-50 text-blue-700'
                    : 'text-gray-600 hover:bg-gray-100 hover:text-gray-800'
                }`}
              >
                {n.label}
              </Link>
            ))}
          </nav>

          {/* Rechte Seite: Health-Badge + Einstellungen + User + Abmelden */}
          <div className='flex items-center gap-1.5 flex-shrink-0'>

            {/* Kiosk Health-Badge */}
            <KioskHealthBadge userRole={userRole} />

            {/* Zahnrad → Einstellungs-Seite */}
            {showSettings && (
              <Link
                to='/settings'
                title='Einstellungen'
                className={`p-2 rounded-lg transition-colors ${
                  settingsActive
                    ? 'bg-blue-50 text-blue-700'
                    : 'text-gray-500 hover:bg-gray-100 hover:text-gray-700'
                }`}
              >
                <svg className='w-5 h-5' fill='none' viewBox='0 0 24 24' stroke='currentColor'>
                  <path strokeLinecap='round' strokeLinejoin='round' strokeWidth={1.75}
                    d='M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z' />
                  <path strokeLinecap='round' strokeLinejoin='round' strokeWidth={1.75} d='M15 12a3 3 0 11-6 0 3 3 0 016 0z' />
                </svg>
              </Link>
            )}

            {/* User-Avatar → Profil */}
            <Link
              to='/profile'
              title={`${userName} · ${ROLE_LABELS[userRole] ?? userRole}`}
              className='flex items-center gap-2 px-2 py-1.5 rounded-lg hover:bg-gray-100 transition-colors'
            >
              <div className='w-7 h-7 rounded-full bg-blue-100 flex items-center justify-center flex-shrink-0'>
                <span className='text-blue-700 font-bold text-xs'>{initials}</span>
              </div>
              <div className='hidden md:block text-left'>
                <p className='text-sm font-medium text-gray-800 leading-tight'>{userName}</p>
                <p className='text-xs text-gray-400 leading-tight'>{ROLE_LABELS[userRole] ?? userRole}</p>
              </div>
            </Link>

            {/* Abmelden */}
            <button
              onClick={logout}
              title='Abmelden'
              className='p-2 rounded-lg text-gray-500 hover:text-red-600 hover:bg-red-50 transition-colors'
            >
              <svg className='w-5 h-5' fill='none' viewBox='0 0 24 24' stroke='currentColor'>
                <path strokeLinecap='round' strokeLinejoin='round' strokeWidth={1.75}
                  d='M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1' />
              </svg>
            </button>
          </div>

        </div>
      </header>

      <main className='max-w-7xl mx-auto px-4 sm:px-6 py-8'>
        {children}
      </main>
    </div>
  )
}
