import { useEffect, useRef, useState } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import { useAuth } from '../context/AuthContext.jsx';
import { useUi }  from '../context/UiContext.jsx';
import { api } from '../api.js';

/* ── Icônes nav ─────────────────────────────────────────────── */
function IconUser() {
  return <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><circle cx="12" cy="8" r="4"/><path d="M4 20c0-4 3.6-7 8-7s8 3 8 7"/></svg>;
}
function IconLock() {
  return <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>;
}

/* ── Dropdown custom style Finary ────────────────────────────── */
const LANGUES = [
  { value: 'fr', label: 'Français' },
  { value: 'en', label: 'English' },
];
const DEVISES = [
  { value: 'EUR', label: '€ - EUR' },
  { value: 'USD', label: '$ - USD' },
  { value: 'GBP', label: '£ - GBP' },
  { value: 'CHF', label: 'CHF' },
  { value: 'CAD', label: 'CA$ - CAD' },
  { value: 'SGD', label: 'SGD' },
];

function ProfileSelect({ label, options, value, onChange }) {
  const [open, setOpen] = useState(false);
  const ref = useRef(null);

  useEffect(() => {
    if (!open) return;
    const h = (e) => { if (!ref.current?.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', h);
    return () => document.removeEventListener('mousedown', h);
  }, [open]);

  const selected = options.find(o => o.value === value);

  return (
    <div ref={ref} className="profile-field">
      <span className="profile-label">{label}</span>
      <div className={`profile-select-trigger${open ? ' open' : ''}`}
        onClick={() => setOpen(o => !o)} role="button" tabIndex={0}
        onKeyDown={e => e.key === 'Enter' && setOpen(o => !o)}>
        <span>{selected?.label}</span>
        <svg width="12" height="12" viewBox="0 0 24 24" fill="none"
          stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"
          style={{ transition: 'transform .15s', transform: open ? 'rotate(180deg)' : 'rotate(0deg)' }}
          aria-hidden="true">
          <path d="M6 9l6 6 6-6"/>
        </svg>
      </div>
      {open && (
        <div className="profile-select-dropdown" role="listbox">
          {options.map(o => (
            <div key={o.value}
              className={`profile-select-option${o.value === value ? ' selected' : ''}`}
              role="option" aria-selected={o.value === value}
              onClick={() => { onChange(o.value); setOpen(false); }}>
              {o.label}
              {o.value === value && (
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none"
                  stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"
                  aria-hidden="true">
                  <polyline points="20 6 9 17 4 12"/>
                </svg>
              )}
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

/* ── Mon profil + Préférences ────────────────────────────────── */
function AccountForm() {
  const { user, updateUser } = useAuth();
  const { langue, setLangue, devise, setDevise } = useUi();

  /* Découpe display_name en prénom / nom */
  const parseName = (dn = '') => {
    const parts = dn.trim().split(' ');
    return parts.length >= 2
      ? { prenom: parts[0], nom: parts.slice(1).join(' ') }
      : { prenom: dn.trim(), nom: '' };
  };

  const initial = parseName(user?.display_name);
  const [prenom, setPrenom] = useState(initial.prenom);
  const [nom,    setNom]    = useState(initial.nom);
  const [infoMsg, setInfoMsg] = useState(null);
  const [infoErr, setInfoErr] = useState(null);
  const [loading, setLoading] = useState(false);

  const save = async () => {
    setInfoErr(null); setInfoMsg(null); setLoading(true);
    try {
      const displayName = [prenom.trim(), nom.trim()].filter(Boolean).join(' ');
      await updateUser({ displayName });
      setInfoMsg('Profil mis à jour.');
    } catch (err) { setInfoErr(err.message); }
    finally { setLoading(false); }
  };

  /* Sauvegarde auto à la perte du focus */
  const handleBlur = () => save();

  return (
    <div className="profile-page">

      {/* ── Mon profil ──────────────────────────────────────── */}
      <section className="profile-section">
        <h2 className="profile-section-title">Mon profil</h2>

        {infoErr && <div className="error" style={{ marginBottom: 12 }}>{infoErr}</div>}
        {infoMsg && <div className="success-msg" style={{ marginBottom: 12 }}>{infoMsg}</div>}

        <div className="profile-grid-2">
          <div className="profile-field">
            <span className="profile-label">Prénom</span>
            <input className="profile-input" value={prenom}
              onChange={e => setPrenom(e.target.value)}
              onBlur={handleBlur}
              placeholder="Prénom" />
          </div>
          <div className="profile-field">
            <span className="profile-label">Nom</span>
            <input className="profile-input" value={nom}
              onChange={e => setNom(e.target.value)}
              onBlur={handleBlur}
              placeholder="NOM" />
          </div>
        </div>

        <div className="profile-field profile-field-full">
          <span className="profile-label">Mon email</span>
          <div className="profile-email-row">
            <span className="profile-email-value">{user?.email}</span>
          </div>
        </div>

        <div style={{ marginTop: 20 }}>
          <button className="profile-manage-btn" type="button" disabled>
            Gérer mon email
          </button>
        </div>
      </section>

      {/* ── Préférences ─────────────────────────────────────── */}
      <section className="profile-section">
        <h2 className="profile-section-title">Préférences</h2>
        <div className="profile-grid-2">
          <ProfileSelect label="Langue"  options={LANGUES} value={langue}  onChange={setLangue} />
          <ProfileSelect label="Devise"  options={DEVISES} value={devise}  onChange={setDevise} />
        </div>
      </section>

      {loading && <p className="text-muted" style={{ fontSize: 'var(--fs-sm)' }}>Enregistrement…</p>}
    </div>
  );
}

/* ── Sécurité — Mot de passe ─────────────────────────────────── */
function SecurityForm() {
  const { updateUser } = useAuth();

  const [pwdForm, setPwdForm] = useState({ currentPassword: '', newPassword: '', confirm: '' });
  const [pwdMsg, setPwdMsg]   = useState(null);
  const [pwdErr, setPwdErr]   = useState(null);
  const [pwdLoading, setPwdLoading] = useState(false);

  const savePwd = async (e) => {
    e.preventDefault(); setPwdErr(null); setPwdMsg(null);
    if (pwdForm.newPassword !== pwdForm.confirm) { setPwdErr('Les mots de passe ne correspondent pas.'); return; }
    if (pwdForm.newPassword.length < 8) { setPwdErr('8 caractères minimum.'); return; }
    setPwdLoading(true);
    try {
      await updateUser({ currentPassword: pwdForm.currentPassword, newPassword: pwdForm.newPassword });
      setPwdMsg('Mot de passe modifié avec succès.');
      setPwdForm({ currentPassword: '', newPassword: '', confirm: '' });
    } catch (err) { setPwdErr(err.message); }
    finally { setPwdLoading(false); }
  };

  const handleBackfillComptes = async () => {
    setLoadingBackfill(true);
    setErrorMsg(null);
    setSuccessMsg(null);
    try {
      const { updated, total } = await api.post('/remboursements/backfill-comptes', {});
      if (updated === 0) {
        setSuccessMsg(`Aucun remboursement à corriger (${total} vérifié${total > 1 ? 's' : ''}).`);
      } else {
        setSuccessMsg(`${updated} remboursement${updated > 1 ? 's' : ''} mis à jour sur ${total} vérifié${total > 1 ? 's' : ''}.`);
      }
      setShowBackfillModal(false);
    } catch (err) {
      setErrorMsg(err.message || 'Une erreur est survenue.');
      setShowBackfillModal(false);
    } finally {
      setLoadingBackfill(false);
    }
  };

  return (
    <div className="card">
      <h3 style={{ margin: '0 0 4px' }}>Mot de passe</h3>
      <p className="text-muted" style={{ margin: '0 0 16px', fontSize: 'var(--fs-sm)' }}>
        Saisissez votre mot de passe actuel puis choisissez-en un nouveau (8 caractères minimum).
      </p>
      {pwdErr && <div className="error">{pwdErr}</div>}
      {pwdMsg && <div className="success-msg">{pwdMsg}</div>}
      <form onSubmit={savePwd}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12, maxWidth: 400 }}>
          <div>
            <label>Mot de passe actuel</label>
            <input type="password" required autoComplete="current-password"
              value={pwdForm.currentPassword}
              onChange={e => setPwdForm({ ...pwdForm, currentPassword: e.target.value })} />
          </div>
          <div>
            <label>Nouveau mot de passe</label>
            <input type="password" required autoComplete="new-password"
              value={pwdForm.newPassword}
              onChange={e => setPwdForm({ ...pwdForm, newPassword: e.target.value })} />
          </div>
          <div>
            <label>Confirmer le nouveau mot de passe</label>
            <input type="password" required autoComplete="new-password"
              value={pwdForm.confirm}
              onChange={e => setPwdForm({ ...pwdForm, confirm: e.target.value })} />
          </div>
        </div>
        <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: 16 }}>
          <button className="primary" type="submit" disabled={pwdLoading}>
            {pwdLoading ? 'Modification…' : 'Modifier le mot de passe'}
          </button>
        </div>
      </form>
    </div>
  );
}

/* ── Page principale ─────────────────────────────────────────── */
export default function MonCompte() {
  const { search } = useLocation();
  const navigate   = useNavigate();

  const section    = new URLSearchParams(search).get('section') || 'profil';
  const setSection = (s) => navigate(`/compte?section=${s}`, { replace: true });

  const SECTIONS = [
    { id: 'profil',    label: 'Mon compte',            icon: <IconUser /> },
{ id: 'securite',  label: 'Sécurité',              icon: <IconLock /> },
  ];

  return (
    <div className="account-layout">

      {/* ── Nav gauche ───────────────────────────────────────── */}
      <aside className="account-sidebar">
        <h1 className="account-title">Mon compte</h1>
        {SECTIONS.map(item => (
          <button
            key={item.id}
            className={`account-nav-item${section === item.id ? ' active' : ''}`}
            onClick={() => setSection(item.id)}
          >
            {item.icon}
            {item.label}
          </button>
        ))}
      </aside>
      {/* ── Contenu ─────────────────────────────────────── */}
      <div className="account-content">
        {section === 'profil'    && <AccountForm />}
        {section === 'securite'  && <SecurityForm />}
      </div>

    </div>
  );
}
