import { useState } from 'react'
import { Monitor } from 'lucide-react'
import { login, register } from '../api/client'

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

  const isRegister = isFirstUser

  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)
    }
  }

  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>

        <form onSubmit={handleSubmit} 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 className="bg-red-950/40 border border-red-800/50 rounded-lg px-3 py-2 text-xs text-red-300">
              {error}
            </div>
          )}

          <div>
            <label className="block text-xs text-gray-400 mb-1.5">Nom d'utilisateur</label>
            <input
              type="text"
              required
              autoFocus
              autoComplete="username"
              value={username}
              onChange={(e) => setUsername(e.target.value)}
              className="w-full bg-gray-800 border border-gray-700 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-indigo-500 transition-colors"
            />
          </div>

          <div>
            <label className="block text-xs text-gray-400 mb-1.5">Mot de passe</label>
            <input
              type="password"
              required
              autoComplete={isRegister ? 'new-password' : 'current-password'}
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              className="w-full bg-gray-800 border border-gray-700 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-indigo-500 transition-colors"
            />
          </div>

          {isRegister && (
            <div>
              <label className="block text-xs text-gray-400 mb-1.5">Confirmer le mot de passe</label>
              <input
                type="password"
                required
                autoComplete="new-password"
                value={password2}
                onChange={(e) => setPassword2(e.target.value)}
                className="w-full bg-gray-800 border border-gray-700 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-indigo-500 transition-colors"
              />
            </div>
          )}

          <button
            type="submit"
            disabled={loading}
            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>
      </div>
    </div>
  )
}
