import { useState } from 'react'
import { loginDesk } from '../lib/auth'

export default function AdminLoginGate({ onSuccess }) {
  const [username, setUsername] = useState('')
  const [password, setPassword] = useState('')
  const [error, setError] = useState('')
  const [busy, setBusy] = useState(false)

  async function handleSubmit(e) {
    e.preventDefault()
    setError('')
    setBusy(true)
    try {
      await loginDesk(username, password)
      onSuccess?.()
    } catch (err) {
      setError(err.message || 'Login falhou')
    } finally {
      setBusy(false)
    }
  }

  return (
    <div className="card login-card" style={{ maxWidth: 420 }}>
      <h2 style={{ marginTop: 0 }}>Área Admin</h2>
      <p className="dns-viewer-meta">
        Se já entrou no <strong>Desk</strong> neste browser, actualize esta página (F5) — a sessão
        partilha automaticamente entre <code>desk</code> e <code>console</code>.
        Alternativa: no painel DNS do setup, <strong>Abrir no Console ↗</strong>.
        Só precisa de password aqui se abriu o Console directamente, sem Desk.
      </p>
      <form onSubmit={handleSubmit}>
        <label className="form-label">
          Utilizador
          <input
            className="form-input"
            value={username}
            onChange={(e) => setUsername(e.target.value)}
            autoComplete="username"
            required
          />
        </label>
        <label className="form-label">
          Senha
          <input
            type="password"
            className="form-input"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            autoComplete="current-password"
            required
          />
        </label>
        {error ? <p className="error-text">{error}</p> : null}
        <button type="submit" className="btn btn-primary" disabled={busy}>
          {busy ? 'Entrando…' : 'Entrar'}
        </button>
      </form>
    </div>
  )
}
