import { useState, useEffect } from 'react'
import { Monitor, Fingerprint } from 'lucide-react'
import { login, register, loginWithPasskey } from '../api/client'
import { inputClass, PasswordInput } from './ui/controls'

export default function LoginPage({ isFirstUser, passkeyEnabled, onAuthenticated }) {
  const [username, setUsername] = useState('')
  const [password, setPassword] = useState('')
  const [password2, setPassword2] = useState('')
  const [error, setError]   = useState(null)
  const [loading, setLoading] = useState(false)
  const [passkeyLoading, setPasskeyLoading] = useState(false)
  const [browserSupportsPasskey, setBrowserSupportsPasskey] = useState(false)

  const isRegister = isFirstUser

  useEffect(() => {
    if (window.PublicKeyCredential) {
      window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()
        .then(available => setBrowserSupportsPasskey(available))
        .catch(() => setBrowserSupportsPasskey(false))
    }
  }, [])

  const handleSubmit = async (e) => {
    e.preventDefault()
    setError(null)

    if (isRegister) {
      if (password !== password2) {
        setError('Les mots de passe ne correspondent pas.')
        return
      }
      if (password.length < 6) {
        setError('Le mot de passe doit contenir au moins 6 caractères.')
        return
      }
    }

    setLoading(true)
    try {
      const data = isRegister
        ? await register(username.trim(), password)
        : await login(username.trim(), password)
      onAuthenticated(data.access_token, data.role)
    } catch (err) {
      setError(err.message)
    } finally {
      setLoading(false)
    }
  }

  const handlePasskeyLogin = async () => {
    setError(null)
    setPasskeyLoading(true)
    try {
      const data = await loginWithPasskey(username.trim() || null)
      onAuthenticated(data.access_token, data.role)
    } catch (err) {
      if (err.name === 'NotAllowedError' || err.message?.includes('NotAllowedError')) {
        setError('Authentification annulée.')
      } else {
        setError(err.message)
      }
    } finally {
      setPasskeyLoading(false)
    }
  }

  const showPasskeyButton = !isRegister && passkeyEnabled && browserSupportsPasskey

  return (
    <div className="min-h-screen bg-gray-950 text-gray-100 flex items-center justify-center px-4">
      <div className="w-full max-w-sm">
        {/* Logo */}
        <div className="flex flex-col items-center mb-8">
          <div className="p-3 rounded-2xl bg-indigo-500/15 mb-3">
            <Monitor size={28} className="text-indigo-400" />
          </div>
          <h1 className="text-xl font-semibold">VPS Monitor</h1>
          <p className="text-sm text-gray-500 mt-1">
            {isRegister ? 'Créer le compte administrateur' : 'Connexion'}
          </p>
        </div>

        <div className="bg-gray-900 border border-gray-800 rounded-2xl p-6 space-y-4">
          {isRegister && (
            <div className="bg-indigo-950/40 border border-indigo-800/50 rounded-lg px-3 py-2 text-xs text-indigo-300">
              Aucun utilisateur n'existe encore. Le premier compte créé sera <strong>admin</strong>.
            </div>
          )}

          {error && (
            <div role="alert" className="bg-red-950/40 border border-red-800/50 rounded-lg px-3 py-2 text-xs text-red-300">
              {error}
            </div>
          )}

          <form onSubmit={handleSubmit} className="space-y-4">
            <div>
              <label htmlFor="login-username" className="block text-xs text-gray-400 mb-1.5">Nom d'utilisateur</label>
              <input
                id="login-username"
                type="text"
                required
                autoFocus
                autoComplete="username"
                value={username}
                onChange={(e) => setUsername(e.target.value)}
                className={inputClass}
              />
            </div>

            <div>
              <label htmlFor="login-password" className="block text-xs text-gray-400 mb-1.5">Mot de passe</label>
              <PasswordInput
                id="login-password"
                required
                autoComplete={isRegister ? 'new-password' : 'current-password'}
                value={password}
                onChange={(e) => setPassword(e.target.value)}
              />
            </div>

            {isRegister && (
              <div>
                <label htmlFor="login-password2" className="block text-xs text-gray-400 mb-1.5">Confirmer le mot de passe</label>
                <PasswordInput
                  id="login-password2"
                  required
                  autoComplete="new-password"
                  value={password2}
                  onChange={(e) => setPassword2(e.target.value)}
                />
              </div>
            )}

            <button
              type="submit"
              disabled={loading || passkeyLoading}
              className="w-full py-2 rounded-lg bg-indigo-600 hover:bg-indigo-500 disabled:opacity-50 text-sm font-medium transition-colors mt-2"
            >
              {loading
                ? 'Chargement…'
                : isRegister
                  ? 'Créer le compte'
                  : 'Se connecter'}
            </button>
          </form>

          {showPasskeyButton && (
            <>
              <div className="relative flex items-center gap-3">
                <div className="flex-1 border-t border-gray-800" />
                <span className="text-xs text-gray-600">ou</span>
                <div className="flex-1 border-t border-gray-800" />
              </div>

              <button
                type="button"
                onClick={handlePasskeyLogin}
                disabled={loading || passkeyLoading}
                className="w-full flex items-center justify-center gap-2 py-2 rounded-lg bg-gray-800 hover:bg-gray-700 disabled:opacity-50 text-sm font-medium transition-colors border border-gray-700"
              >
                <Fingerprint size={16} className="text-indigo-400" />
                {passkeyLoading ? 'Vérification…' : 'Se connecter avec une passkey'}
              </button>
            </>
          )}
        </div>
      </div>
    </div>
  )
}
