import { useState, useRef } from 'react'
import { useNavigate } from 'react-router-dom'
import { useAuth } from '../../context/AuthContext'
import { api } from '../../api/client'

interface LoginResponse {
  access_token: string
  refresh_token: string
  totp_required?: boolean
  partial_token?: string
}

export function MobileLoginPage() {
  const { login } = useAuth()
  const navigate = useNavigate()

  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')
  const [totpCode, setTotpCode] = useState('')
  const [partialToken, setPartialToken] = useState<string | null>(null)
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)

  const totpInputRef = useRef<HTMLInputElement>(null)

  // Schritt 1: E-Mail + Passwort
  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault()
    setLoading(true)
    setError(null)
    try {
      const res = await api.post<LoginResponse>('/auth/login', { email, password })
      if (res.totp_required && res.partial_token) {
        // 2FA erforderlich → TOTP-Formular zeigen
        setPartialToken(res.partial_token)
        setTimeout(() => totpInputRef.current?.focus(), 100)
      } else {
        // Direkt eingeloggt
        localStorage.setItem('access_token', res.access_token)
        localStorage.setItem('refresh_token', res.refresh_token)
        await login(email, password)
        navigate('/mobile', { replace: true })
      }
    } catch (e: unknown) {
      setError(e instanceof Error ? e.message : 'Anmeldung fehlgeschlagen')
    } finally {
      setLoading(false)
    }
  }

  // Schritt 2: TOTP-Code
  const handleTotp = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!partialToken) return
    setLoading(true)
    setError(null)
    try {
      const res = await api.post<LoginResponse>('/auth/totp/login', {
        partial_token: partialToken,
        code: totpCode,
      })
      localStorage.setItem('access_token', res.access_token)
      localStorage.setItem('refresh_token', res.refresh_token)
      // AuthContext-State synchronisieren (löst Re-Render aus)
      window.dispatchEvent(new Event('storage'))
      navigate('/mobile', { replace: true })
    } catch (e: unknown) {
      setError(e instanceof Error ? e.message : 'Ungültiger Code')
      setTotpCode('')
      totpInputRef.current?.focus()
    } finally {
      setLoading(false)
    }
  }

  return (
    <div
      className='min-h-screen bg-gray-50 flex flex-col items-center justify-center px-6'
      style={{ paddingTop: 'env(safe-area-inset-top)', paddingBottom: 'env(safe-area-inset-bottom)' }}
    >
      {/* Logo */}
      <div className='flex flex-col items-center mb-10 gap-3'>
        <div className='w-16 h-16 bg-blue-600 rounded-2xl flex items-center justify-center shadow-lg'>
          <span className='text-white font-bold text-2xl'>TM</span>
        </div>
        <h1 className='text-2xl font-bold text-gray-900'>TimeMaster</h1>
        <p className='text-sm text-gray-500'>
          {partialToken ? 'Zwei-Faktor-Authentifizierung' : 'Bitte melde dich an'}
        </p>
      </div>

      {/* Fehler-Banner */}
      {error && (
        <div className='w-full max-w-sm mb-4 bg-red-50 border border-red-200 rounded-xl px-4 py-3 text-sm text-red-700'>
          {error}
        </div>
      )}

      {/* Formular */}
      <div className='w-full max-w-sm bg-white rounded-2xl border border-gray-200 shadow-sm p-6'>

        {!partialToken ? (
          /* ── Login-Formular ── */
          <form onSubmit={handleLogin} className='flex flex-col gap-4'>
            <div className='flex flex-col gap-1.5'>
              <label className='text-sm font-medium text-gray-700'>E-Mail</label>
              <input
                type='email'
                value={email}
                onChange={e => setEmail(e.target.value)}
                placeholder='deine@email.de'
                required
                autoComplete='email'
                className='min-h-[52px] px-4 rounded-xl border border-gray-300 text-gray-900 text-base focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent'
              />
            </div>
            <div className='flex flex-col gap-1.5'>
              <label className='text-sm font-medium text-gray-700'>Passwort</label>
              <input
                type='password'
                value={password}
                onChange={e => setPassword(e.target.value)}
                placeholder='••••••••'
                required
                autoComplete='current-password'
                className='min-h-[52px] px-4 rounded-xl border border-gray-300 text-gray-900 text-base focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent'
              />
            </div>
            <button
              type='submit'
              disabled={loading || !email || !password}
              className='min-h-[52px] mt-2 rounded-xl bg-blue-600 active:bg-blue-800 text-white font-semibold text-base transition-colors disabled:opacity-50 flex items-center justify-center gap-2'
            >
              {loading
                ? <span className='animate-spin rounded-full h-5 w-5 border-2 border-white border-t-transparent' />
                : 'Anmelden'
              }
            </button>
          </form>

        ) : (
          /* ── TOTP-Formular ── */
          <form onSubmit={handleTotp} className='flex flex-col gap-4'>
            <div className='flex flex-col items-center gap-2 mb-2'>
              <div className='w-12 h-12 bg-blue-50 rounded-xl flex items-center justify-center'>
                <span className='text-2xl'>🔐</span>
              </div>
              <p className='text-sm text-gray-500 text-center'>
                Gib den 6-stelligen Code aus deiner Authenticator-App ein.
              </p>
            </div>
            <input
              ref={totpInputRef}
              type='text'
              inputMode='numeric'
              pattern='[0-9]{6}'
              maxLength={6}
              value={totpCode}
              onChange={e => setTotpCode(e.target.value.replace(/\D/g, ''))}
              placeholder='000000'
              required
              autoComplete='one-time-code'
              className='min-h-[64px] px-4 rounded-xl border border-gray-300 text-gray-900 text-3xl font-mono tracking-widest text-center focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent'
            />
            <button
              type='submit'
              disabled={loading || totpCode.length !== 6}
              className='min-h-[52px] rounded-xl bg-blue-600 active:bg-blue-800 text-white font-semibold text-base transition-colors disabled:opacity-50 flex items-center justify-center gap-2'
            >
              {loading
                ? <span className='animate-spin rounded-full h-5 w-5 border-2 border-white border-t-transparent' />
                : 'Bestätigen'
              }
            </button>
            <button
              type='button'
              onClick={() => { setPartialToken(null); setTotpCode(''); setError(null) }}
              className='text-sm text-gray-400 text-center py-1 active:text-gray-600'
            >
              ← Zurück zur Anmeldung
            </button>
          </form>
        )}
      </div>

      {/* Link zur Desktop-Version */}
      <a
        href='/login'
        className='mt-6 text-sm text-gray-400 active:text-gray-600'
      >
        Desktop-Version öffnen
      </a>
    </div>
  )
}
