import { useState, useEffect } from 'react'
import { Link, useLocation, useNavigate } from 'react-router-dom'
import { useAuth } from '../context/AuthContext'

export function LoginPage() {
  const { login }                       = useAuth()
  const location                        = useLocation()
  const navigate                        = useNavigate()

  // Auf Mobilgeräten / Tablets → mobile Login-Seite
  useEffect(() => {
    const isMobile = window.innerWidth < 1024 || /Mobi|Android|Tablet|iPad|iPhone/i.test(navigator.userAgent)
    if (isMobile) navigate('/mobile/login', { replace: true })
  }, [])
  const [email, setEmail]               = useState('')
  const [password, setPassword]         = useState('')
  const [error, setError]               = useState('')
  const [loading, setLoading]           = useState(false)
  const successMsg                      = (location.state as { message?: string } | null)?.message

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault()
    setError('')
    setLoading(true)
    try {
      await login(email, password)
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : 'Anmeldung fehlgeschlagen')
    } finally {
      setLoading(false)
    }
  }

  const inputClass =
    'mt-1 w-full border border-gray-300 rounded-lg px-3 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-blue-400 focus:border-transparent'

  return (
    <div className='min-h-screen bg-gradient-to-br from-blue-50 to-indigo-100 flex items-center justify-center p-4'>
      <div className='w-full max-w-sm bg-white rounded-2xl shadow-lg p-8'>

        {/* Logo */}
        <div className='flex items-center gap-2 mb-6'>
          <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='text-lg font-bold text-gray-800'>TimeMaster</span>
        </div>

        <h1 className='text-xl font-semibold text-gray-800 mb-1'>Anmelden</h1>
        <p className='text-sm text-gray-500 mb-6'>Willkommen zurück</p>

        {successMsg && (
          <div className='text-sm text-green-700 bg-green-50 border border-green-200 rounded-lg px-3 py-2.5 mb-4'>
            {successMsg}
          </div>
        )}

        <form onSubmit={handleSubmit} className='space-y-4'>
          <label className='block'>
            <span className='text-sm font-medium text-gray-700'>E-Mail-Adresse</span>
            <input
              type='email'
              value={email}
              onChange={e => setEmail(e.target.value)}
              required
              autoFocus
              className={inputClass}
              placeholder='max@muster-gmbh.de'
            />
          </label>

          <label className='block'>
            <div className='flex items-center justify-between'>
              <span className='text-sm font-medium text-gray-700'>Passwort</span>
              <Link to='/forgot-password' className='text-xs text-blue-600 hover:underline'>
                Vergessen?
              </Link>
            </div>
            <input
              type='password'
              value={password}
              onChange={e => setPassword(e.target.value)}
              required
              className={inputClass}
            />
          </label>

          {error && (
            <div className='text-sm text-red-700 bg-red-50 border border-red-200 rounded-lg px-3 py-2.5'>
              {error}
            </div>
          )}

          <button
            type='submit'
            disabled={loading}
            className='w-full py-2.5 text-sm font-semibold text-white bg-blue-600 rounded-lg hover:bg-blue-700 disabled:opacity-50 transition-colors'
          >
            {loading ? 'Anmelden…' : 'Anmelden'}
          </button>
        </form>

        <p className='text-center text-sm text-gray-500 mt-6'>
          Noch kein Konto?{' '}
          <Link to='/register' className='text-blue-600 hover:underline font-medium'>
            Jetzt registrieren
          </Link>
        </p>
      </div>
    </div>
  )
}
