// Page Profil utilisateur
// - Permet de modifier le pseudo social (Discord/Twitch)
// - Permet de changer l'email et le mot de passe
// - Liste les commandes de l'utilisateur et ouvre un détail en modal
function ProfilePage({ navigate }) {
  const { user, setUser } = window.AuthContext.useAuth();
  const toast = window.Toast.useToast();
  // Champs du profil
  const [email, setEmail] = React.useState(user?.email || '');
  const [currentPwForEmail, setCurrentPwForEmail] = React.useState('');
  const [currentPw, setCurrentPw] = React.useState('');
  const [newPw, setNewPw] = React.useState('');
  const [socialHandle, setSocialHandle] = React.useState(user?.social_handle || '');
  const [postalAddress, setPostalAddress] = React.useState(user?.postal_address || '');
  // Etats de chargement pour éviter le double-submit
  const [loadingSocial, setLoadingSocial] = React.useState(false);
  const [loadingEmail, setLoadingEmail] = React.useState(false);
  const [loadingPw, setLoadingPw] = React.useState(false);
  // Commandes de l'utilisateur
  const [orders, setOrders] = React.useState([]);
  const [ordersLoading, setOrdersLoading] = React.useState(true);
  const [openOrder, setOpenOrder] = React.useState(null); // { order, items }
  const [loadingOrder, setLoadingOrder] = React.useState(false);

  // Sync champs quand le contexte utilisateur (Auth) change
  React.useEffect(() => { setEmail(user?.email || ''); }, [user?.email]);
  React.useEffect(() => { setSocialHandle(user?.social_handle || ''); }, [user?.social_handle]);
  React.useEffect(() => { setPostalAddress(user?.postal_address || ''); }, [user?.postal_address]);
  // Charge l'historique des commandes au montage (et quand l'id change)
  React.useEffect(() => {
    if (!user) return;
    (async () => {
      try {
        setOrdersLoading(true);
        const res = await window.ProfileAPI.orders();
        setOrders(Array.isArray(res.items) ? res.items : []);
      } catch (e) {
        toast.error('Erreur de chargement des commandes');
      } finally { setOrdersLoading(false); }
    })();
  }, [user?.id]);

  // Soumission: mise à jour email (nécessite le mot de passe actuel)
  async function submitEmail(e) {
    e.preventDefault();
    try {
      setLoadingEmail(true);
      const res = await window.ProfileAPI.updateEmail(email, currentPwForEmail);
      setUser(res.user);
      setCurrentPwForEmail('');
      toast.success('Email mis à jour.');
    } catch (err) {
      const msg = err?.error?.message || err?.message || 'Erreur mise à jour email';
      toast.error(msg);
    } finally { setLoadingEmail(false); }
  }

  // Soumission: changement de mot de passe
  async function submitPassword(e) {
    e.preventDefault();
    try {
      setLoadingPw(true);
      await window.ProfileAPI.updatePassword(currentPw, newPw);
      setCurrentPw(''); setNewPw('');
      toast.success('Mot de passe mis à jour.');
    } catch (err) {
      const msg = err?.error?.message || err?.message || 'Erreur mise à jour mot de passe';
      toast.error(msg);
    } finally { setLoadingPw(false); }
  }

  // Soumission: mise à jour du pseudo Discord/Twitch
  async function submitSocial(e) {
    e.preventDefault();
    try {
      setLoadingSocial(true);
      const res = await window.ProfileAPI.updateSocialHandle(socialHandle);
      setUser(res.user);
    } catch (err) {
      const msg = err?.error?.message || err?.message || 'Erreur mise à jour du pseudo';
      toast.error(msg);
    } finally { setLoadingSocial(false); }
  }

  // Soumission: mise à jour de l'adresse postale
  const [loadingAddress, setLoadingAddress] = React.useState(false);
  async function submitAddress(e) {
    e.preventDefault();
    try {
      setLoadingAddress(true);
      const res = await window.ProfileAPI.updatePostalAddress(postalAddress);
      setUser(res.user);
      toast.success('Adresse postale mise à jour.');
    } catch (err) {
      const msg = err?.error?.message || err?.message || 'Erreur mise à jour de l\'adresse';
      toast.error(msg);
    } finally { setLoadingAddress(false); }
  }

  if (!user) {
    return (
      <div className="container">
        <p>Veuillez vous connecter pour accéder à votre profil.</p>
        <button onClick={() => navigate('/login')}>Se connecter</button>
      </div>
    );
  }

  // Helpers formatage (dates et montants)
  function fmtDate(s) {
    if (!s) return '';
    try { return new Date(String(s).replace(' ', 'T')).toLocaleString(); } catch { return String(s); }
  }
  const fmtMoney = (cents) => new Intl.NumberFormat('fr-FR', { style: 'currency', currency: 'EUR' }).format((Number(cents||0))/100);

  // Ouvre la modal de commande avec les items
  async function viewOrder(id) {
    try {
      setLoadingOrder(true);
      const data = await window.ProfileAPI.orderDetail(id);
      setOpenOrder(data);
    } catch (e) {
      toast.error("Impossible de charger la commande");
    } finally { setLoadingOrder(false); }
  }

  return (
    <div className="container" style={{ maxWidth: 640 }}>
      <h2>Mon profil</h2>

      {/* Section pseudo social (Discord/Twitch) */}
      <section style={{ background: 'var(--brand-card)', padding: 16, borderRadius: 12, border: '1px solid var(--brand-border)', boxShadow: 'var(--brand-shadow)', marginBottom: 20 }}>
        <h3>Mon pseudo Discord / Twitch</h3>
        <form onSubmit={submitSocial} style={{ display: 'grid', gap: 12 }}>
          <label>
            Pseudo Discord / Twitch
            <input type="text" value={socialHandle} onChange={e=>setSocialHandle(e.target.value)} placeholder="ex: wenyn#1234 ou @wenyn" />
          </label>
          <div>
            <button type="submit" disabled={loadingSocial}>{loadingSocial ? 'En cours…' : 'Mettre à jour le pseudo'}</button>
          </div>
        </form>
      </section>
      {/* Section email (avec vérification du mot de passe actuel) */}
      {/* Section adresse postale */}
      <section style={{ background: 'var(--brand-card)', padding: 16, borderRadius: 12, border: '1px solid var(--brand-border)', boxShadow: 'var(--brand-shadow)', marginBottom: 20 }}>
        <h3>Mon adresse postale</h3>
        <form onSubmit={submitAddress} style={{ display: 'grid', gap: 12 }}>
          <label>
            Adresse postale (pour la livraison)
            <textarea value={postalAddress} onChange={e=>setPostalAddress(e.target.value)} placeholder="Nom\nAdresse\nCode postal Ville" rows={4} />
          </label>
          <div>
            <button type="submit" disabled={loadingAddress}>{loadingAddress ? 'En cours…' : 'Mettre à jour l\'adresse'}</button>
          </div>
        </form>
      </section>
      {/* Section email (avec vérification du mot de passe actuel) */}
      <section style={{ background: 'var(--brand-card)', padding: 16, borderRadius: 12, border: '1px solid var(--brand-border)', boxShadow: 'var(--brand-shadow)', marginBottom: 20 }}>
        <h3>Changer mon adresse email</h3>
        <form onSubmit={submitEmail} style={{ display: 'grid', gap: 12 }}>
          <label>
            Nouvelle adresse email
            <input type="email" value={email} onChange={e=>setEmail(e.target.value)} required />
          </label>
          <label>
            Mot de passe actuel
            <input type="password" value={currentPwForEmail} onChange={e=>setCurrentPwForEmail(e.target.value)} required />
          </label>
          <div>
            <button type="submit" disabled={loadingEmail}>{loadingEmail ? 'En cours…' : 'Mettre à jour l\'email'}</button>
          </div>
        </form>
      </section>

      {/* Section mot de passe */}
      <section style={{ background: 'var(--brand-card)', padding: 16, borderRadius: 12, border: '1px solid var(--brand-border)', boxShadow: 'var(--brand-shadow)' }}>
        <h3>Changer mon mot de passe</h3>
        <form onSubmit={submitPassword} style={{ display: 'grid', gap: 12 }}>
          <label>
            Mot de passe actuel
            <input type="password" value={currentPw} onChange={e=>setCurrentPw(e.target.value)} required />
          </label>
          <label>
            Nouveau mot de passe
            <input type="password" value={newPw} onChange={e=>setNewPw(e.target.value)} minLength={6} required />
          </label>
          <div>
            <button type="submit" disabled={loadingPw}>{loadingPw ? 'En cours…' : 'Mettre à jour le mot de passe'}</button>
          </div>
        </form>
      </section>

      {/* Liste des commandes */}
      <section style={{ background: 'var(--brand-card)', padding: 16, borderRadius: 12, border: '1px solid var(--brand-border)', boxShadow: 'var(--brand-shadow)', marginTop: 20 }}>
        <h3>Mes commandes</h3>
        {ordersLoading ? (
          <p>Chargement…</p>
        ) : orders.length === 0 ? (
          <p>Vous n'avez pas encore de commande.</p>
        ) : (
          <div style={{ display: 'grid', gap: 10 }}>
            {orders.map(o => (
              <div key={o.id} style={{ display: 'flex', justifyContent: 'space-between', border: '1px solid var(--brand-border)', borderRadius: 10, padding: 12 }}>
                <div>
                  <div style={{ fontWeight: 700 }}>Commande #{o.id}</div>
                  <div style={{ color: 'var(--brand-muted)' }}>{fmtDate(o.created_at)}</div>
                </div>
                <div style={{ textAlign: 'right' }}>
                  <div style={{ marginBottom: 6 }}>
                    <span className={`badge status ${o.status}`}>{{ pending:'En attente', processed:'Traitée', canceled:'Annulée' }[o.status] || o.status}</span>
                  </div>
                  <div style={{ fontWeight: 800, marginBottom: 8 }}>{fmtMoney(o.total_cents)}</div>
                  <button className="button" onClick={() => viewOrder(o.id)} disabled={loadingOrder && openOrder?.order?.id === o.id}>
                    {loadingOrder && openOrder?.order?.id === o.id ? 'Ouverture…' : 'Voir le détail'}
                  </button>
                </div>
              </div>
            ))}
          </div>
        )}
      </section>

      {/* Modal de détail de commande */}
      {openOrder && (
        <div className="modal-backdrop" onClick={() => setOpenOrder(null)}>
          <div className="modal" onClick={(e)=>e.stopPropagation()}>
            <div className="modal-header">
              <h3>Commande #{openOrder.order.id}</h3>
              <button onClick={()=>setOpenOrder(null)} aria-label="Fermer">×</button>
            </div>
            <div className="modal-body">
              <p><b>Statut:</b> <span className={`badge status ${openOrder.order.status}`}>{{ pending:'En attente', processed:'Traitée', canceled:'Annulée' }[openOrder.order.status] || openOrder.order.status}</span></p>
              <p><b>Date:</b> {fmtDate(openOrder.order.created_at)}</p>
              <table style={{ width:'100%', borderCollapse:'collapse' }}>
                <thead>
                  <tr><th align="left">Article</th><th>Qté</th><th>PU</th><th>Sous-total</th></tr>
                </thead>
                <tbody>
                  {openOrder.items.map((it, idx) => (
                    <tr key={idx}>
                      <td style={{ padding:'6px 0' }}>{it.name}</td>
                      <td align="center">{it.quantity}</td>
                      <td align="right">{fmtMoney(it.unit_price_cents)}</td>
                      <td align="right">{fmtMoney(it.unit_price_cents * it.quantity)}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
              <div style={{ textAlign:'right', marginTop: 10, fontWeight: 800 }}>
                Total {fmtMoney(openOrder.items.reduce((acc, it) => acc + it.unit_price_cents * it.quantity, 0))}
              </div>
            </div>
            <div className="modal-footer">
              <button onClick={()=>setOpenOrder(null)}>Fermer</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

window.Pages = window.Pages || {};
window.Pages.Profile = ProfilePage;
