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 VerifyEmailModal from '../components/VerifyEmailModal.jsx';

export default function Login() {
  const { login, loginWithGoogle } = useAuth();
  const toast = useToast();
  const navigate = useNavigate();
  const location = useLocation();
  const [form, setForm] = useState({ email: '', password: '' });
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);
  const [captchaToken, setCaptchaToken] = useState('');
  const [captchaReset, setCaptchaReset] = useState(0);
  const [verifyFor, setVerifyFor] = useState(''); // email awaiting OTP verification
  const onCaptcha = useCallback((t) => setCaptchaToken(t), []);

  const goAfterAuth = useCallback((user) => {
    toast.success(`Welcome back, ${user.name.split(' ')[0]}!`);
    const isStaff = user.role === 'ADMIN' || user.role === 'SUPER_ADMIN';
    const dest = location.state?.from || (isStaff ? '/admin' : '/dashboard');
    navigate(dest, { replace: true });
  }, [toast, location.state, navigate]);

  const submit = async (e) => {
    e.preventDefault();
    setError('');
    if (RECAPTCHA_ENABLED && !captchaToken) {
      setError('Please complete the "I\'m not a robot" check.');
      return;
    }
    setLoading(true);
    try {
      goAfterAuth(await login(form.email, form.password, captchaToken));
    } catch (err) {
      // The token is single-use — reset the widget so the user can retry.
      setCaptchaToken('');
      setCaptchaReset((n) => n + 1);
      // Unverified account (e.g. just created by an admin): a fresh code was emailed —
      // pop up the OTP verification modal. They can't proceed until they verify.
      if (err.response?.data?.details?.needsVerification) {
        toast.info('Please verify your email — we sent you a code.');
        setVerifyFor(form.email);
        return;
      }
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  const handleGoogle = useCallback(async (credential) => {
    setError('');
    try {
      goAfterAuth(await loginWithGoogle(credential));
    } catch (err) {
      setError(err.message);
    }
  }, [loginWithGoogle, goAfterAuth]);

  return (
    <div className="container page" style={{ maxWidth: 440 }}>
      <div className="card mt-4">
        {/* <div className="auth-brand">CN</div> */}
        <h2>Welcome back</h2>
        <p className="muted">Log in to continue practicing.</p>
        {error && <div className="alert alert-error">{error}</div>}
        <form onSubmit={submit}>
          <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">
            <div className="row-between" style={{ alignItems: 'baseline' }}>
              <label className="label">Password</label>
              <Link to="/forgot-password" className="muted" style={{ fontSize: '0.85rem' }}>
                Forgot password?
              </Link>
            </div>
            <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 ? 'Logging in…' : 'Log in'}
          </button>
        </form>
        <div className="auth-divider">or</div>
        <GoogleSignInButton onCredential={handleGoogle} text="signin_with" />
        <p className="muted mt-3" style={{ marginBottom: 0 }}>
          No account? <Link to="/register">Create one</Link>
        </p>
      </div>

      {verifyFor && (
        <VerifyEmailModal
          email={verifyFor}
          onClose={() => setVerifyFor('')}
          onVerified={(user) => { setVerifyFor(''); goAfterAuth(user); }}
        />
      )}
    </div>
  );
}
