import { useState } from 'react'

const TotpForm = ({ onSubmit, isLoading, onBack }) => {
  const [totpCode, setTotpCode] = useState('')

  const handleSubmit = (event) => {
    event.preventDefault()
    onSubmit(totpCode.replace(/\s+/g, ''))
  }

  return (
    <form onSubmit={handleSubmit} className="d-flex flex-column gap-3">
      <div>
        <label htmlFor="totpCode" className="form-label">Codigo TOTP</label>
        <input
          id="totpCode"
          name="totpCode"
          type="text"
          pattern="[0-9]{6}"
          inputMode="numeric"
          className="form-control"
          value={totpCode}
          onChange={(event) => setTotpCode(event.target.value)}
          placeholder="123456"
          required
        />
        <div className="form-text">Introduce el codigo de tu app de autenticacion</div>
      </div>
      <div className="d-flex gap-2">
        {onBack && (
          <button
            type="button"
            className="btn btn-outline-secondary"
            onClick={onBack}
            disabled={isLoading}
          >
            Configurar 2FA
          </button>
        )}
        <button type="submit" className="btn btn-success ms-auto" disabled={isLoading}>
          {isLoading ? 'Validando...' : 'Validar codigo'}
        </button>
      </div>
    </form>
  )
}

export default TotpForm
