import { useRef, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useAuthStore } from '../stores/auth'
import { Shield, KeyRound } from 'lucide-react'

export default function Login() {
  const [username, setUsername] = useState('')
  const [password, setPassword] = useState('')
  const [error, setError] = useState('')
  const [loading, setLoading] = useState(false)

  // 2FA-Schritt
  const [totpRequired, setTotpRequired] = useState(false)
  const [totpToken, setTotpToken] = useState('')
  const [totpCode, setTotpCode] = useState('')
  const totpRef = useRef(null)

  const { login, validateTOTP } = useAuthStore()
  const navigate = useNavigate()

  const handleSubmit = async (e) => {
    e.preventDefault()
    setError('')
    setLoading(true)
    try {
      const result = await login(username, password)
      if (result?.totp_required) {
        setTotpToken(result.totp_token)
        setTotpRequired(true)
        setTimeout(() => totpRef.current?.focus(), 100)
      } else {
        navigate('/')
      }
    } catch (err) {
      setError(err.message || 'Login fehlgeschlagen')
    } finally {
      setLoading(false)
    }
  }

  const handleTOTP = async (e) => {
    e.preventDefault()
    if (totpCode.length !== 6) return
    setError('')
    setLoading(true)
    try {
      await validateTOTP(totpToken, totpCode)
      navigate('/')
    } catch (err) {
      setError(err.message || 'Ungültiger Code')
      setTotpCode('')
      totpRef.current?.focus()
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="min-h-screen flex items-center justify-center bg-gray-950">
      <div className="w-full max-w-sm">
        <div className="text-center mb-8">
          <Shield className="w-12 h-12 text-orange-500 mx-auto mb-3" />
          <h1 className="text-2xl font-bold text-white">RMM</h1>
          <p className="text-gray-500 text-sm mt-1">Remote Monitoring & Management</p>
        </div>

        {!totpRequired ? (
          <form onSubmit={handleSubmit} className="bg-gray-900 rounded-lg border border-gray-800 p-6 space-y-4">
            {error && (
              <div className="bg-red-900/30 border border-red-800 text-red-400 px-3 py-2 rounded text-sm">
                {error}
              </div>
            )}
            <div>
              <label className="block text-sm text-gray-400 mb-1">Benutzer</label>
              <input
                type="text"
                value={username}
                onChange={(e) => setUsername(e.target.value)}
                className="w-full bg-gray-800 border border-gray-700 rounded px-3 py-2 text-white focus:outline-none focus:border-orange-500"
                autoFocus
              />
            </div>
            <div>
              <label className="block text-sm text-gray-400 mb-1">Passwort</label>
              <input
                type="password"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                className="w-full bg-gray-800 border border-gray-700 rounded px-3 py-2 text-white focus:outline-none focus:border-orange-500"
              />
            </div>
            <button
              type="submit"
              disabled={loading}
              className="w-full bg-orange-600 hover:bg-orange-700 disabled:bg-gray-700 text-white font-medium py-2 rounded transition-colors"
            >
              {loading ? 'Anmelden...' : 'Anmelden'}
            </button>
          </form>
        ) : (
          <form onSubmit={handleTOTP} className="bg-gray-900 rounded-lg border border-gray-800 p-6 space-y-4">
            <div className="text-center mb-2">
              <KeyRound className="w-8 h-8 text-orange-500 mx-auto mb-2" />
              <p className="text-sm text-gray-300 font-medium">2-Faktor-Authentifizierung</p>
              <p className="text-xs text-gray-500 mt-1">Code aus der Authenticator-App eingeben</p>
            </div>
            {error && (
              <div className="bg-red-900/30 border border-red-800 text-red-400 px-3 py-2 rounded text-sm">
                {error}
              </div>
            )}
            <div>
              <label className="block text-sm text-gray-400 mb-1">6-stelliger Code</label>
              <input
                ref={totpRef}
                type="text"
                inputMode="numeric"
                pattern="[0-9]*"
                maxLength={6}
                value={totpCode}
                onChange={(e) => {
                  const v = e.target.value.replace(/\D/g, '')
                  setTotpCode(v)
                }}
                className="w-full bg-gray-800 border border-gray-700 rounded px-3 py-2 text-white text-center text-xl tracking-widest focus:outline-none focus:border-orange-500"
                placeholder="000000"
              />
            </div>
            <button
              type="submit"
              disabled={loading || totpCode.length !== 6}
              className="w-full bg-orange-600 hover:bg-orange-700 disabled:bg-gray-700 text-white font-medium py-2 rounded transition-colors"
            >
              {loading ? 'Prüfen...' : 'Bestätigen'}
            </button>
            <button
              type="button"
              onClick={() => { setTotpRequired(false); setError(''); setTotpCode('') }}
              className="w-full text-gray-500 hover:text-gray-300 text-sm py-1"
            >
              Zurück
            </button>
          </form>
        )}
      </div>
    </div>
  )
}
