import { useState, useCallback } from 'react';
import { Link, useNavigate, useLocation } from 'react-router-dom';
import { useAuth } from '../context/AuthContext.jsx';
import { useToast } from '../context/ToastContext.jsx';
import GoogleSignInButton from '../components/GoogleSignInButton.jsx';
import PasswordInput from '../components/PasswordInput.jsx';
import Recaptcha, { RECAPTCHA_ENABLED } from '../components/Recaptcha.jsx';
import useCountdown from '../hooks/useCountdown.js';

const OTP_SECONDS = 60;

export default function Register() {
  const { register, loginWithGoogle, verifyEmail, resendOtp } = useAuth();
  const toast = useToast();
  const navigate = useNavigate();
  const location = useLocation();
  // A login attempt on an unverified account redirects here to finish verification.
  const pendingEmail = location.state?.verifyEmail || '';
  const [form, setForm] = useState({ name: '', email: pendingEmail, password: '' });
  const [step, setStep] = useState(pendingEmail ? 'verify' : 'form'); // 'form' | 'verify'
  const [code, setCode] = useState('');
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);
  const [seconds, startCountdown] = useCountdown(pendingEmail ? OTP_SECONDS : 0);
  const [captchaToken, setCaptchaToken] = useState('');
  const [captchaReset, setCaptchaReset] = useState(0);
  const onCaptcha = useCallback((t) => setCaptchaToken(t), []);

  const submit = async (e) => {
    e.preventDefault();
    setError('');
    if (form.password.length < 8) {
      setError('Password must be at least 8 characters.');
      return;
    }
    if (RECAPTCHA_ENABLED && !captchaToken) {
      setError('Please complete the "I\'m not a robot" check.');
      return;
    }
    setLoading(true);
    try {
      await register(form.name, form.email, form.password, captchaToken);
      toast.success('We sent a verification code to your email.');
      setStep('verify');
      startCountdown(OTP_SECONDS);
    } catch (err) {
      // The token is single-use — reset the widget so the user can retry.
      setCaptchaToken('');
      setCaptchaReset((n) => n + 1);
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  const verify = async (e) => {
    e.preventDefault();
    setError('');
    setLoading(true);
    try {
      await verifyEmail(form.email, code);
      toast.success('Email verified — welcome to CertsNexus!');
      navigate('/dashboard', { replace: true });
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  const resend = async () => {
    setError('');
    try {
      await resendOtp(form.email, 'EMAIL_VERIFY');
      toast.success('A new code is on its way.');
      setCode('');
      startCountdown(OTP_SECONDS);
    } catch (err) {
      setError(err.message);
    }
  };

  const handleGoogle = useCallback(async (credential) => {
    setError('');
    try {
      const user = await loginWithGoogle(credential);
      toast.success(`Welcome to CertsNexus, ${user.name.split(' ')[0]}!`);
      navigate('/dashboard', { replace: true });
    } catch (err) {
      setError(err.message);
    }
  }, [loginWithGoogle, toast, navigate]);

  return (
    <div className="container page" style={{ maxWidth: 440 }}>
      <div className="card mt-4">
        {/* <div className="auth-brand">CN</div> */}
        {step === 'form' ? (
          <>
            <h2>Create your account</h2>
            <p className="muted">Start practicing in under a minute.</p>
            {error && <div className="alert alert-error">{error}</div>}
            <form onSubmit={submit}>
              <div className="field">
                <label className="label">Full name</label>
                <input className="input" required value={form.name}
                  onChange={(e) => setForm({ ...form, name: e.target.value })} placeholder="Jane Doe" />
              </div>
              <div className="field">
                <label className="label">Email</label>
                <input className="input" type="email" required value={form.email}
                  onChange={(e) => setForm({ ...form, email: e.target.value })} placeholder="you@example.com" />
              </div>
              <div className="field">
                <label className="label">Password</label>
                <PasswordInput required value={form.password}
                  onChange={(e) => setForm({ ...form, password: e.target.value })} placeholder="At least 8 characters" />
              </div>
              <div className="field"><Recaptcha onChange={onCaptcha} resetSignal={captchaReset} /></div>
              <button className="btn btn-block btn-lg" disabled={loading || (RECAPTCHA_ENABLED && !captchaToken)}>
                {loading ? 'Creating…' : 'Create account'}
              </button>
            </form>
            <div className="auth-divider">or</div>
            <GoogleSignInButton onCredential={handleGoogle} text="signup_with" />
            <p className="muted mt-3" style={{ marginBottom: 0 }}>
              Already have an account? <Link to="/login">Log in</Link>
            </p>
          </>
        ) : (
          <>
            <h2>Verify your email</h2>
            <p className="muted">
              Enter the 6-digit code we sent to <b>{form.email}</b>.
            </p>
            {error && <div className="alert alert-error">{error}</div>}
            <form onSubmit={verify}>
              <div className="field">
                <label className="label">Verification code</label>
                <input
                  className="input"
                  inputMode="numeric"
                  autoComplete="one-time-code"
                  maxLength={6}
                  required
                  value={code}
                  onChange={(e) => setCode(e.target.value.replace(/\D/g, ''))}
                  placeholder="123456"
                  style={{ letterSpacing: '6px', textAlign: 'center', fontSize: '1.3rem' }}
                />
              </div>
              <button className="btn btn-block btn-lg" disabled={loading || code.length !== 6}>
                {loading ? 'Verifying…' : 'Verify email'}
              </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>
            <p className="muted mt-3" style={{ marginBottom: 0, textAlign: 'center' }}>
              Entered the wrong email?{' '}
              <button
                type="button"
                className="btn btn-ghost btn-sm"
                onClick={() => { setStep('form'); setCode(''); setError(''); }}
              >
                Go back
              </button>
            </p>
          </>
        )}
      </div>
    </div>
  );
}
