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

// Wrap défini en dehors du composant pour éviter le remontage à chaque frappe
function Wrap({ appInfo, children }) {
  return (
    <div style={{ display: 'flex', minHeight: '100dvh' }}>
      <div className="login-bg-col" style={{ flex: '1 1 50%', display: 'none', position: 'relative', overflow: 'hidden', background: '#0d0d0d' }}>
        <img src="/login-bg.jpg" alt="" aria-hidden="true" onError={e => { e.target.style.display = 'none'; }}
          style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover', opacity: 0.85 }} />
        <div style={{ position: 'absolute', bottom: 40, left: 40, color: '#fff', display: 'flex', alignItems: 'center', gap: 12 }}>
          {appInfo.iconUrl && <img src={appInfo.iconUrl} alt="" width={36} height={36} style={{ borderRadius: 8 }} />}
          <span style={{ fontSize: 18, fontWeight: 600, letterSpacing: '-0.3px' }}>{appInfo.appName}</span>
        </div>
      </div>
      <div style={{ flex: '1 1 50%', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: '48px 24px', background: 'var(--background, #fff)', minWidth: 0 }}>
        <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 }}>{children}</div>
      </div>
      <style>{'@media (min-width: 768px) { .login-bg-col { display: block !important; } }'}</style>
    </div>
  );
}

export default function InvitationRegister() {
  const { token }   = useParams();
  const navigate    = useNavigate();
  const [appInfo, setAppInfo] = useState({ appName: 'Crowdlending Tracker', iconUrl: null, minPasswordLength: 8 });
  const [inv, setInv]         = useState(null);   // { email, role, expiresAt }
  const [status, setStatus]   = useState('loading'); // loading | valid | invalid | done
  const [errMsg, setErrMsg]   = useState('');
  const [form, setForm]       = useState({ displayName: '', password: '', confirm: '' });
  const [busy, setBusy]       = useState(false);
  const [err, setErr]         = useState(null);

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

  useEffect(() => {
    fetch(`/api/invitations/${token}`)
      .then(async r => {
        if (!r.ok) {
          const d = await r.json().catch(() => ({}));
          throw new Error(d.error || 'Lien invalide.');
        }
        return r.json();
      })
      .then(data => { setInv(data); setStatus('valid'); })
      .catch(e  => { setErrMsg(e.message); setStatus('invalid'); });
  }, [token]);

  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));

  const submit = async (e) => {
    e.preventDefault();
    if (form.password !== form.confirm) { setErr('Les mots de passe ne correspondent pas.'); return; }
    setBusy(true); setErr(null);
    try {
      const r = await fetch(`/api/invitations/${token}/register`, {
        method:  'POST',
        headers: { 'Content-Type': 'application/json' },
        body:    JSON.stringify({ displayName: form.displayName || undefined, password: form.password }),
      });
      if (!r.ok) {
        const d = await r.json().catch(() => ({}));
        throw new Error(d.error || 'Erreur lors de la création du compte.');
      }
      setStatus('done');
    } catch (e) { setErr(e.message); }
    finally { setBusy(false); }
  };

  // ── Chargement ───────────────────────────────────────────────────────────
  if (status === 'loading') {
    return (
      <Wrap appInfo={appInfo}>
        <p style={{ textAlign: 'center', color: 'var(--text-muted)' }}>Vérification du lien…</p>
      </Wrap>
    );
  }

  // ── Lien invalide / expiré ───────────────────────────────────────────────
  if (status === 'invalid') {
    return (
      <Wrap appInfo={appInfo}>
        <div style={{ textAlign: 'center' }}>
          <div style={{ width: 56, height: 56, borderRadius: '50%', background: '#fef2f2', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 20px' }}>
            <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="#dc2626" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
              <circle cx="12" cy="12" r="10"/><line x1="15" y1="9" x2="9" y2="15"/><line x1="9" y1="9" x2="15" y2="15"/>
            </svg>
          </div>
          <h1 style={{ margin: '0 0 10px', fontSize: 22, fontWeight: 700, color: 'var(--text)' }}>Lien invalide</h1>
          <p style={{ margin: '0 0 28px', color: 'var(--text-muted)', fontSize: 14, lineHeight: 1.6 }}>{errMsg}</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' }}>
            Retour à la connexion
          </Link>
        </div>
      </Wrap>
    );
  }

  // ── Succès ───────────────────────────────────────────────────────────────
  if (status === 'done') {
    return (
      <Wrap appInfo={appInfo}>
        <div style={{ textAlign: 'center' }}>
          <div style={{ width: 56, height: 56, borderRadius: '50%', background: '#f0fdf4', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 20px' }}>
            <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="#16a34a" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
              <circle cx="12" cy="12" r="10"/><polyline points="9 12 11 14 15 10"/>
            </svg>
          </div>
          <h1 style={{ margin: '0 0 10px', fontSize: 22, fontWeight: 700, color: 'var(--text)' }}>Compte créé !</h1>
          <p style={{ margin: '0 0 28px', color: 'var(--text-muted)', fontSize: 14, lineHeight: 1.6 }}>
            Votre compte a été activé avec succès. Vous pouvez maintenant vous connecter.
          </p>
          <button onClick={() => navigate('/login')} style={{ width: '100%', padding: '11px 0', background: 'var(--primary, #1e40af)', color: '#fff', border: 'none', borderRadius: 8, fontSize: 15, fontWeight: 600, cursor: 'pointer' }}>
            Se connecter
          </button>
        </div>
      </Wrap>
    );
  }

  // ── Formulaire ───────────────────────────────────────────────────────────
  const roleLabel = inv?.role === 'admin' ? 'Administrateur' : 'Utilisateur';

  return (
    <Wrap appInfo={appInfo}>
      <div style={{ marginBottom: 28 }}>
        <h1 style={{ margin: '0 0 6px', fontSize: 26, fontWeight: 700, letterSpacing: '-0.5px', color: 'var(--text)' }}>
          Finaliser votre inscription
        </h1>
        <p style={{ margin: 0, color: 'var(--text-muted)', fontSize: 14 }}>
          Vous avez été invité en tant que <strong>{roleLabel}</strong>.
        </p>
      </div>

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

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

        {/* Email — verrouillé */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
          <label style={{ fontSize: 14, fontWeight: 500, color: 'var(--text)' }}>Adresse email</label>
          <div style={{ position: 'relative' }}>
            <input
              className="form-input"
              type="email"
              value={inv?.email || ''}
              readOnly
              style={{ width: '100%', background: 'var(--surface-2)', color: 'var(--text-muted)', cursor: 'not-allowed', paddingRight: 36 }}
            />
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"
              style={{ position: 'absolute', right: 12, top: '50%', transform: 'translateY(-50%)', color: 'var(--text-muted)', pointerEvents: 'none' }}>
              <rect x="3" y="11" width="18" height="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/>
            </svg>
          </div>
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
          <label style={{ fontSize: 14, fontWeight: 500, color: 'var(--text)' }}>Nom d'affichage <span style={{ color: 'var(--text-muted)', fontWeight: 400 }}>(facultatif)</span></label>
          <input className="form-input" type="text" autoComplete="off" placeholder="Prénom Nom" value={form.displayName} onChange={e => set('displayName', e.target.value)} style={{ width: '100%' }} />
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
          <label style={{ fontSize: 14, fontWeight: 500, color: 'var(--text)' }}>Mot de passe <span style={{ color: 'var(--text-muted)', fontWeight: 400 }}>(8 car. min.)</span></label>
          <input className="form-input" type="password" required minLength={appInfo.minPasswordLength || 8} autoComplete="new-password" placeholder="••••••••" value={form.password} onChange={e => set('password', e.target.value)} style={{ width: '100%' }} />
          <PasswordStrength password={form.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={form.confirm} onChange={e => set('confirm', e.target.value)} 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 ? 'Création…' : 'Créer mon compte'}
        </button>

      </form>

      <p style={{ marginTop: 24, textAlign: 'center', fontSize: 13, color: 'var(--text-muted)' }}>
        Déjà inscrit ?{' '}
        <Link to="/login" style={{ color: 'var(--text)', fontWeight: 500, textDecoration: 'underline' }}>Se connecter</Link>
      </p>
    </Wrap>
  );
}
