import { useEffect, useState } from 'react'
import api from '../api'

export default function Login() {
  const [oidcConfig, setOidcConfig] = useState({ enabled: false, label: 'Se connecter via SSO' })
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    api.get('/auth/oidc/config')
      .then(res => setOidcConfig(res.data))
      .catch(() => {})
      .finally(() => setLoading(false))
  }, [])

  const handleSso = () => {
    window.location.href = '/api/auth/oidc/login'
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 to-blue-100 flex items-center justify-center p-4">
      <div className="bg-white rounded-2xl shadow-lg p-8 w-full max-w-sm text-center">
        <div className="text-5xl mb-3">🏠</div>
        <h1 className="text-2xl font-bold text-gray-900">Gestion Locative</h1>
        <p className="text-gray-500 mt-1 mb-8">Connectez-vous à votre espace</p>

        {loading ? (
          <div className="flex justify-center py-4">
            <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
          </div>
        ) : oidcConfig.enabled ? (
          <button type="button" onClick={handleSso}
            className="w-full flex items-center justify-center gap-2 py-3 px-4 bg-blue-600 hover:bg-blue-700 text-white rounded-xl font-semibold text-base transition-colors shadow">
            🔑 {oidcConfig.label}
          </button>
        ) : (
          <div className="bg-orange-50 border border-orange-200 rounded-xl p-4 text-sm text-orange-700">
            ⚠️ Le SSO n'est pas configuré.<br />Contactez l'administrateur.
          </div>
        )}
      </div>
    </div>
  )
}

