import { useState, useEffect } from 'react';
import { Link, useNavigate, useSearchParams } from 'react-router-dom';
import PasswordStrength from '../components/PasswordStrength.jsx';
import AuthBgCol from '../components/AuthBgCol.jsx';

export default function ResetPassword() {
  const [params]    = useSearchParams();
  const navigate    = useNavigate();
  const token       = params.get('token') || '';

  const [password,  setPassword]  = useState('');
  const [password2, setPassword2] = useState('');
  const [status,    setStatus]    = useState(null); // null | 'done' | 'error'
  const [errMsg,    setErrMsg]    = useState('');
  const [busy,      setBusy]      = useState(false);
  const [appInfo,   setAppInfo]   = useState({ appName: 'Crowdlending Tracker', iconUrl: null });

  useEffect(() => {
    fetch('/api/app-info')
      .then(r => r.json())
      .then(d => setAppInfo(d))
      .catch(() => {});
  }, []);

  const submit = async (e) => {
    e.preventDefault();
    if (password !== password2) { setErrMsg('Les mots de passe ne correspondent pas.'); setStatus('error'); return; }
    setErrMsg(''); setBusy(true);
    try {
      const res  = await fetch('/api/auth/reset-password', {
        method:  'POST',
        headers: { 'Content-Type': 'application/json' },
        body:    JSON.stringify({ token, password }),
      });
      const data = await res.json();
      if (!res.ok) { setErrMsg(data.error || 'Une erreur est survenue.'); setStatus('error'); }
      else { setStatus('done'); setTimeout(() => navigate('/login'), 3000); }
    } catch {
      setErrMsg('Impossible de joindre le serveur.'); setStatus('error');
    } finally { setBusy(false); }
  };

  return (
    <div style={{ display: 'flex', minHeight: '100dvh' }}>

      <AuthBgCol appInfo={appInfo} />


      {/* ── Colonne droite — formulaire ──────────────────────── */}
      <div style={{
        flex: '1 1 50%',
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        justifyContent: 'center',
        padding: '48px 24px',
        background: 'var(--background, #fff)',
        minWidth: 0,
      }}>

        {/* Logo + nom */}
        <div style={{
          display: 'flex',
          flexDirection: 'column',
          alignItems: 'center',
          gap: 10,
          marginBottom: 32,
        }}>
          {appInfo.iconUrl && (
            <img src={appInfo.iconUrl} alt={appInfo.appName}
                 width={52} height={52} style={{ borderRadius: 12 }} />
          )}
          <span style={{
            fontSize: 20, fontWeight: 700,
            color: 'var(--text)', letterSpacing: '-0.4px',
          }}>
            {appInfo.appName}
          </span>
        </div>

        <div style={{ width: '100%', maxWidth: 360 }}>

          {!token ? (
            /* ── Lien invalide ── */
            <div style={{ textAlign: 'center' }}>
              <p style={{ color: 'var(--danger)', marginBottom: 20 }}>
                Lien de réinitialisation invalide ou manquant.
              </p>
              <Link to="/forgot-password" style={{
                color: 'var(--text)', fontWeight: 500, textDecoration: 'underline',
              }}>
                Faire une nouvelle demande
              </Link>
            </div>
          ) : status === 'done' ? (
            /* ── Succès ── */
            <div style={{ textAlign: 'center' }}>
              <div style={{
                width: 52, height: 52, borderRadius: '50%',
                background: 'var(--success-bg, #f0fdf4)',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                margin: '0 auto 20px',
              }}>
                <svg width="24" height="24" viewBox="0 0 24 24" fill="none">
                  <path d="M20 6L9 17l-5-5" stroke="var(--success, #16a34a)" strokeWidth="2.2"
                        strokeLinecap="round" strokeLinejoin="round"/>
                </svg>
              </div>
              <h1 style={{
                margin: '0 0 10px', fontSize: 22, fontWeight: 700,
                letterSpacing: '-0.4px', color: 'var(--text)',
              }}>Mot de passe mis à jour</h1>
              <p style={{ margin: '0 0 28px', color: 'var(--text-muted)', fontSize: 14 }}>
                Redirection vers la connexion dans quelques secondes…
              </p>
              <Link to="/login" style={{
                display: 'block', width: '100%', padding: '11px 0',
                background: 'var(--primary, #1e40af)', color: '#fff',
                borderRadius: 8, fontSize: 15, fontWeight: 600,
                textDecoration: 'none', textAlign: 'center',
              }}>
                Se connecter
              </Link>
            </div>
          ) : (
            /* ── Formulaire ── */
            <>
              <div style={{ marginBottom: 28 }}>
                <h1 style={{
                  margin: '0 0 6px', fontSize: 26, fontWeight: 700,
                  letterSpacing: '-0.5px', color: 'var(--text)',
                }}>
                  Nouveau mot de passe
                </h1>
                <p style={{ margin: 0, color: 'var(--text-muted)', fontSize: 14 }}>
                  Choisissez un mot de passe d'au moins 8 caractères.
                </p>
              </div>

              <form onSubmit={submit} style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>

                {status === 'error' && (
                  <div style={{
                    padding: '10px 14px', borderRadius: 8, fontSize: 14,
                    background: 'var(--danger-bg, #fef2f2)',
                    color: 'var(--danger, #dc2626)',
                    border: '1px solid var(--danger-light, #fca5a5)',
                  }}>
                    {errMsg}
                  </div>
                )}

                <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                  <label style={{ fontSize: 14, fontWeight: 500, color: 'var(--text)' }}>
                    Nouveau mot de passe
                  </label>
                  <input
                    className="form-input"
                    type="password" required minLength={appInfo.minPasswordLength || 8}
                    autoComplete="new-password"
                    placeholder="••••••••"
                    value={password}
                    onChange={e => { setPassword(e.target.value); setStatus(null); }}
                    style={{ width: '100%' }}
                  />
                  <PasswordStrength password={password} minLength={appInfo.minPasswordLength || 8} />
                </div>

                <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                  <label style={{ fontSize: 14, fontWeight: 500, color: 'var(--text)' }}>
                    Confirmer le mot de passe
                  </label>
                  <input
                    className="form-input"
                    type="password" required minLength={appInfo.minPasswordLength || 8}
                    autoComplete="new-password"
                    placeholder="••••••••"
                    value={password2}
                    onChange={e => { setPassword2(e.target.value); setStatus(null); }}
                    style={{ width: '100%' }}
                  />
                </div>

                <button
                  type="submit"
                  disabled={busy}
                  style={{
                    marginTop: 4, width: '100%',
                    padding: '11px 0',
                    background: busy ? 'var(--text-muted)' : 'var(--primary, #1e40af)',
                    color: '#fff',
                    border: 'none', borderRadius: 8,
                    fontSize: 15, fontWeight: 600,
                    cursor: busy ? 'not-allowed' : 'pointer',
                    transition: 'background 0.15s',
                  }}
                >
                  {busy ? 'Enregistrement…' : 'Réinitialiser le mot de passe'}
                </button>

              </form>

              <p style={{
                marginTop: 24, textAlign: 'center',
                fontSize: 13, color: 'var(--text-muted)',
              }}>
                <Link to="/login" style={{
                  color: 'var(--text)', fontWeight: 500, textDecoration: 'underline',
                }}>
                  Retour à la connexion
                </Link>
              </p>
            </>
          )}

        </div>
      </div>
    </div>
  );
}
