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

const OTP_SECONDS = 60;

export default function ForgotPassword() {
  const { requestPasswordReset, resetPassword, resendOtp } = useAuth();
  const toast = useToast();
  const navigate = useNavigate();
  const [step, setStep] = useState('request'); // 'request' | 'reset'
  const [email, setEmail] = useState('');
  const [code, setCode] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);
  const [seconds, startCountdown] = useCountdown(0);

  const request = async (e) => {
    e.preventDefault();
    setError('');
    setLoading(true);
    try {
      await requestPasswordReset(email);
      toast.success('If that email is registered, a reset code has been sent.');
      setStep('reset');
      startCountdown(OTP_SECONDS);
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  const reset = async (e) => {
    e.preventDefault();
    setError('');
    if (password.length < 8) {
      setError('Password must be at least 8 characters.');
      return;
    }
    setLoading(true);
    try {
      await resetPassword(email, code, password);
      toast.success('Password updated — please log in.');
      navigate('/login', { replace: true });
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

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

  return (
    <div className="container page" style={{ maxWidth: 440 }}>
      <div className="card mt-4">
        <div className="auth-brand">CN</div>
        {step === 'request' ? (
          <>
            <h2>Forgot password</h2>
            <p className="muted">Enter your email and we'll send a reset code.</p>
            {error && <div className="alert alert-error">{error}</div>}
            <form onSubmit={request}>
              <div className="field">
                <label className="label">Email</label>
                <input className="input" type="email" required value={email}
                  onChange={(e) => setEmail(e.target.value)} placeholder="you@example.com" />
              </div>
              <button className="btn btn-block btn-lg" disabled={loading}>
                {loading ? 'Sending…' : 'Send reset code'}
              </button>
            </form>
            <p className="muted mt-3" style={{ marginBottom: 0 }}>
              Remembered it? <Link to="/login">Back to log in</Link>
            </p>
          </>
        ) : (
          <>
            <h2>Reset password</h2>
            <p className="muted">
              Enter the 6-digit code sent to <b>{email}</b> and choose a new password.
            </p>
            {error && <div className="alert alert-error">{error}</div>}
            <form onSubmit={reset}>
              <div className="field">
                <label className="label">Reset 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>
              <div className="field">
                <label className="label">New password</label>
                <PasswordInput required value={password}
                  onChange={(e) => setPassword(e.target.value)} placeholder="At least 8 characters" />
              </div>
              <button className="btn btn-block btn-lg" disabled={loading || code.length !== 6}>
                {loading ? 'Updating…' : 'Update password'}
              </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' }}>
              <Link to="/login">Back to log in</Link>
            </p>
          </>
        )}
      </div>
    </div>
  );
}
