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

const OTP_SECONDS = 60;

export default function Account() {
  const { user, updateProfile, changePassword, requestEmailChange, verifyEmailChange } = useAuth();
  const toast = useToast();
  const location = useLocation();
  const passwordRef = useRef(null);

  // ----- Profile (name) -----
  const [name, setName] = useState(user?.name || '');
  const [savingName, setSavingName] = useState(false);

  // ----- Email change -----
  const [newEmail, setNewEmail] = useState('');
  const [emailStep, setEmailStep] = useState('idle'); // 'idle' | 'verify'
  const [emailCode, setEmailCode] = useState('');
  const [emailBusy, setEmailBusy] = useState(false);
  const [seconds, startCountdown] = useCountdown(0);

  // ----- Password -----
  const [pw, setPw] = useState({ current: '', next: '', confirm: '' });
  const [pwBusy, setPwBusy] = useState(false);

  // Keep the name field in sync once the user loads.
  useEffect(() => {
    if (user?.name) setName((n) => n || user.name);
  }, [user]);

  // Deep-link from the navbar "Change password" menu item.
  useEffect(() => {
    if (location.hash === '#password' && passwordRef.current) {
      passwordRef.current.scrollIntoView({ behavior: 'smooth', block: 'start' });
    }
  }, [location.hash]);

  const saveName = async (e) => {
    e.preventDefault();
    if (name.trim().length < 2) return toast.error('Name must be at least 2 characters.');
    if (name.trim() === user.name) return toast.info('That is already your name.');
    setSavingName(true);
    try {
      await updateProfile(name.trim());
      toast.success('Profile updated.');
    } catch (err) {
      toast.error(err.message);
    } finally {
      setSavingName(false);
    }
  };

  const sendEmailCode = async (e) => {
    e.preventDefault();
    setEmailBusy(true);
    try {
      await requestEmailChange(newEmail);
      toast.success('We sent a verification code to your new email.');
      setEmailStep('verify');
      startCountdown(OTP_SECONDS);
    } catch (err) {
      toast.error(err.message);
    } finally {
      setEmailBusy(false);
    }
  };

  const confirmEmail = async (e) => {
    e.preventDefault();
    setEmailBusy(true);
    try {
      await verifyEmailChange(newEmail, emailCode);
      toast.success('Email address updated.');
      setEmailStep('idle');
      setNewEmail('');
      setEmailCode('');
    } catch (err) {
      toast.error(err.message);
    } finally {
      setEmailBusy(false);
    }
  };

  const resendEmailCode = async () => {
    try {
      await requestEmailChange(newEmail);
      toast.success('A new code is on its way.');
      setEmailCode('');
      startCountdown(OTP_SECONDS);
    } catch (err) {
      toast.error(err.message);
    }
  };

  const savePassword = async (e) => {
    e.preventDefault();
    if (pw.next.length < 8) return toast.error('New password must be at least 8 characters.');
    if (pw.next !== pw.confirm) return toast.error('New password and confirmation do not match.');
    setPwBusy(true);
    try {
      await changePassword(pw.current, pw.next);
      toast.success('Password changed successfully.');
      setPw({ current: '', next: '', confirm: '' });
    } catch (err) {
      toast.error(err.message);
    } finally {
      setPwBusy(false);
    }
  };

  return (
    <div className="container page" style={{ maxWidth: 680 }}>
      <h1>Account settings</h1>
      <p className="muted">Manage your profile, email address and password.</p>

      {/* Profile */}
      <div className="card mt-3">
        <h3>Profile</h3>
        <form onSubmit={saveName}>
          <div className="field">
            <label className="label">Full name</label>
            <input className="input" value={name} required
              onChange={(e) => setName(e.target.value)} placeholder="Your name" />
          </div>
          <button className="btn" disabled={savingName}>{savingName ? 'Saving…' : 'Save changes'}</button>
        </form>
      </div>

      {/* Email */}
      <div className="card mt-3">
        <div className="row-between" style={{ alignItems: 'center' }}>
          <h3 style={{ margin: 0 }}>Email address</h3>
          <span className={`badge ${user.emailVerified ? 'badge-green' : 'badge-amber'}`}>
            {user.emailVerified ? 'Verified' : 'Unverified'}
          </span>
        </div>
        <p className="muted mt-2" style={{ marginBottom: 16 }}>
          Current: <b style={{ color: 'var(--ink)' }}>{user.email}</b>
        </p>

        {emailStep === 'idle' ? (
          <form onSubmit={sendEmailCode}>
            <div className="field">
              <label className="label">New email</label>
              <input className="input" type="email" value={newEmail} required
                onChange={(e) => setNewEmail(e.target.value)} placeholder="new@example.com" />
            </div>
            <button className="btn" disabled={emailBusy}>
              {emailBusy ? 'Sending…' : 'Send verification code'}
            </button>
          </form>
        ) : (
          <form onSubmit={confirmEmail}>
            <div className="alert alert-info">
              Enter the 6-digit code we sent to <b>{newEmail}</b> to confirm the change.
            </div>
            <div className="field">
              <label className="label">Verification code</label>
              <input className="input" inputMode="numeric" autoComplete="one-time-code" maxLength={6} required
                value={emailCode} onChange={(e) => setEmailCode(e.target.value.replace(/\D/g, ''))}
                placeholder="123456" style={{ letterSpacing: '6px', textAlign: 'center', fontSize: '1.3rem' }} />
            </div>
            <div className="row wrap" style={{ gap: 10 }}>
              <button className="btn" disabled={emailBusy || emailCode.length !== 6}>
                {emailBusy ? 'Updating…' : 'Verify & update email'}
              </button>
              {seconds > 0 ? (
                <span className="muted" style={{ alignSelf: 'center' }}>Resend in {seconds}s</span>
              ) : (
                <button type="button" className="btn btn-ghost" onClick={resendEmailCode}>Resend code</button>
              )}
              <button type="button" className="btn btn-ghost"
                onClick={() => { setEmailStep('idle'); setEmailCode(''); }}>
                Cancel
              </button>
            </div>
          </form>
        )}
      </div>

      {/* Password */}
      <div className="card mt-3" id="password" ref={passwordRef}>
        <h3>Change password</h3>
        <form onSubmit={savePassword}>
          <div className="field">
            <label className="label">Current password</label>
            <PasswordInput value={pw.current} required autoComplete="current-password"
              onChange={(e) => setPw({ ...pw, current: e.target.value })} placeholder="Current password" />
          </div>
          <div className="field">
            <label className="label">New password</label>
            <PasswordInput value={pw.next} required autoComplete="new-password"
              onChange={(e) => setPw({ ...pw, next: e.target.value })} placeholder="At least 8 characters" />
          </div>
          <div className="field">
            <label className="label">Confirm new password</label>
            <PasswordInput value={pw.confirm} required autoComplete="new-password"
              onChange={(e) => setPw({ ...pw, confirm: e.target.value })} placeholder="Re-enter new password" />
          </div>
          <button className="btn" disabled={pwBusy}>{pwBusy ? 'Updating…' : 'Update password'}</button>
        </form>
      </div>
    </div>
  );
}
