import { useState, useEffect } from 'react'
import { Navigate } from 'react-router-dom'
import { useAuth } from '../../context/AuthContext'
import { MobileBottomNav } from './MobileBottomNav'
import { MobileStampScreen } from './MobileStampScreen'
import { MobileTodayScreen } from './MobileTodayScreen'
import { MobileProfileScreen } from './MobileProfileScreen'
import { MobileAbsencesScreen } from './MobileAbsencesScreen'

type Screen = 'stamp' | 'today' | 'absences' | 'profile'

const SCREEN_TITLES: Record<Screen, string> = {
  stamp:    'Zeiterfassung',
  today:    'Heute',
  absences: 'Abwesenheiten',
  profile:  'Profil',
}

export function MobilePage() {
  const { token } = useAuth()
  const [screen, setScreen] = useState<Screen>('stamp')
  const [time, setTime] = useState('')

  // Uhrzeit im Header live aktualisieren
  useEffect(() => {
    const update = () => {
      setTime(new Date().toLocaleTimeString('de-DE', { hour: '2-digit', minute: '2-digit' }))
    }
    update()
    const id = setInterval(update, 1000)
    return () => clearInterval(id)
  }, [])

  if (!token) return <Navigate to='/mobile/login' replace />

  return (
    <div
      className='min-h-screen bg-gray-50 flex flex-col'
      style={{ paddingTop: 'env(safe-area-inset-top)' }}
    >
      {/* Header */}
      <header className='bg-white border-b border-gray-200 sticky top-0 z-10'>
        <div className='flex items-center justify-between px-4 h-14'>
          <div className='flex items-center gap-2'>
            <div className='w-7 h-7 bg-blue-600 rounded-lg flex items-center justify-center'>
              <span className='text-white font-bold text-xs'>TM</span>
            </div>
            <span className='font-bold text-gray-800 text-sm'>TimeMaster</span>
          </div>
          <div className='text-right'>
            <p className='text-base font-mono font-semibold text-gray-800 leading-none'>{time}</p>
            <p className='text-xs text-gray-400 leading-none mt-0.5'>
              {new Date().toLocaleDateString('de-DE', { weekday: 'short', day: '2-digit', month: '2-digit' })}
            </p>
          </div>
        </div>
        {/* Screen-Titel */}
        <div className='px-4 pb-3'>
          <h1 className='text-xl font-bold text-gray-900'>{SCREEN_TITLES[screen]}</h1>
        </div>
      </header>

      {/* Content */}
      <main
        className='flex-1 overflow-y-auto'
        style={{ paddingBottom: 'calc(72px + env(safe-area-inset-bottom))' }}
      >
        {screen === 'stamp'    && <MobileStampScreen />}
        {screen === 'today'    && <MobileTodayScreen />}
        {screen === 'absences' && <MobileAbsencesScreen />}
        {screen === 'profile'  && <MobileProfileScreen />}
      </main>

      {/* Bottom Navigation */}
      <MobileBottomNav active={screen} onChange={setScreen} />
    </div>
  )
}
