import { useState } from 'react';
import { createPortal } from 'react-dom';
import { useAuth } from '../context/AuthContext.jsx';
import useCountdown from '../hooks/useCountdown.js';

const OTP_SECONDS = 60;

/**
 * OTP "verify your email" popup shown on login when an account is not yet
 * verified (e.g. a user the super admin just created). The user can't proceed
 * until they enter the emailed code; verifying logs them straight in.
 *
 * Props:
 *   email       — the address awaiting verification (a fresh code was just sent)
 *   onClose()   — dismiss without verifying (stays logged out)
 *   onVerified(user) — called after a successful verification (already logged in)
 */
export default function VerifyEmailModal({ email, onClose, onVerified }) {
  const { verifyEmail, resendOtp } = useAuth();
  const [code, setCode] = useState('');
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);
  const [seconds, startCountdown] = useCountdown(OTP_SECONDS);

  const submit = async (e) => {
    e.preventDefault();
    setError('');
    setLoading(true);
    try {
      const data = await verifyEmail(email, code);
      onVerified(data.user);
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  const resend = async () => {
    setError('');
    try {
      await resendOtp(email, 'EMAIL_VERIFY');
      setCode('');
      startCountdown(OTP_SECONDS);
    } catch (err) {
      setError(err.message);
    }
  };

  // Render at the document root so the full-screen overlay isn't clipped by the
  // narrow login container (matches the confirm/logout modal).
  return createPortal(
    <div className="modal-overlay" onMouseDown={onClose}>
      <div className="modal" role="dialog" aria-modal="true" onMouseDown={(e) => e.stopPropagation()}>
        <div className="modal-body">
          <div className="modal-icon default">✉️</div>
          <h3>Verify your email</h3>
          <p>Enter the 6-digit code we sent to <b>{email}</b> to continue.</p>
          {error && <div className="alert alert-error">{error}</div>}
          <form onSubmit={submit}>
            <input
              className="input"
              inputMode="numeric"
              autoComplete="one-time-code"
              maxLength={6}
              required
              autoFocus
              value={code}
              onChange={(e) => setCode(e.target.value.replace(/\D/g, ''))}
              placeholder="123456"
              style={{ letterSpacing: '6px', textAlign: 'center', fontSize: '1.3rem' }}
            />
            <button className="btn btn-block btn-lg mt-2" disabled={loading || code.length !== 6}>
              {loading ? 'Verifying…' : 'Verify & continue'}
            </button>
          </form>
          <div className="mt-3" style={{ textAlign: 'center' }}>
            {seconds > 0 ? (
              <span className="muted">Resend code in {seconds}s</span>
            ) : (
              <button type="button" className="btn btn-ghost btn-sm" onClick={resend}>Resend code</button>
            )}
          </div>
        </div>
        <div className="modal-actions">
          <button className="btn btn-ghost" onClick={onClose}>Cancel</button>
        </div>
      </div>
    </div>,
    document.body
  );
}
