// ─── PlanChanges.jsx — Historique des modifications du plan trésorerie ────────
// Pas de build, pas d'import/export — tout est global (React CDN).

function PlanChangesView({ C }) {
  const [entries, setEntries]       = React.useState([]);
  const [loading, setLoading]       = React.useState(true);
  const [error, setError]           = React.useState(null);
  const [expanded, setExpanded]     = React.useState(new Set());
  const [filterProjet, setFilterProjet] = React.useState('');
  const [filterSource, setFilterSource] = React.useState('');

  // ── Couleurs source ────────────────────────────────────────────────────────
  const SOURCE_META = {
    manual:        { label: 'Manuel',        color: '#2563eb', bg: '#eff6ff' },
    status_change: { label: 'Statut lot',    color: '#7c3aed', bg: '#f5f3ff' },
    appel_eg:      { label: 'Appel EG',      color: '#d97706', bg: '#fffbeb' },
    facture:       { label: 'Facture',       color: '#059669', bg: '#f0fdf4' },
  };

  function sourceMeta(s) {
    return SOURCE_META[s] || { label: s || '?', color: '#6b7280', bg: '#f9fafb' };
  }

  // ── Chargement ─────────────────────────────────────────────────────────────
  async function load() {
    setLoading(true);
    setError(null);
    try {
      const params = new URLSearchParams();
      if (filterProjet) params.set('projet_id', filterProjet);
      if (filterSource) params.set('source', filterSource);
      const r = await fetch('/api/plan-changes?' + params.toString());
      if (!r.ok) throw new Error('Erreur ' + r.status);
      const d = await r.json();
      setEntries(d.summary || []);
    } catch (e) {
      setError(e.message);
    } finally {
      setLoading(false);
    }
  }

  React.useEffect(() => { load(); }, []);

  // ── Helpers formatage ──────────────────────────────────────────────────────
  function fmtDate(iso) {
    if (!iso) return '—';
    const d = new Date(iso);
    return d.toLocaleDateString('fr-FR', { day: '2-digit', month: '2-digit', year: '2-digit' })
      + ' ' + d.toLocaleTimeString('fr-FR', { hour: '2-digit', minute: '2-digit' });
  }

  function fmtEur(n) {
    if (n == null) return '—';
    const v = Number(n);
    const s = Math.abs(v).toLocaleString('fr-FR', { minimumFractionDigits: 0, maximumFractionDigits: 0 });
    return (v >= 0 ? '+' : '−') + ' ' + s + ' €';
  }

  function deltaColor(n) {
    if (n == null) return C.muted;
    return Number(n) >= 0 ? '#059669' : '#dc2626';
  }

  function toggleExpand(id) {
    setExpanded(prev => {
      const next = new Set(prev);
      next.has(id) ? next.delete(id) : next.add(id);
      return next;
    });
  }

  // ── Projets disponibles pour filtre ───────────────────────────────────────
  const projets = React.useMemo(() => {
    const seen = new Map();
    for (const e of entries) {
      if (e.projet_id && !seen.has(e.projet_id)) seen.set(e.projet_id, e.projet_nom || e.projet_id);
    }
    return [...seen.entries()];
  }, [entries]);

  // ── Filtrage local ─────────────────────────────────────────────────────────
  const filtered = entries.filter(e => {
    if (filterProjet && e.projet_id !== filterProjet) return false;
    if (filterSource && e.source !== filterSource) return false;
    return true;
  });

  // ── Styles ─────────────────────────────────────────────────────────────────
  const th = { padding: '8px 12px', textAlign: 'left', fontSize: 11, fontWeight: 700,
               color: C.muted, borderBottom: '1px solid ' + C.border, whiteSpace: 'nowrap' };
  const td = { padding: '8px 12px', fontSize: 13, borderBottom: '1px solid ' + C.border, verticalAlign: 'top' };

  // ── Render ──────────────────────────────────────────────────────────────────
  return (
    <div style={{ padding: '20px 24px', maxWidth: 1100, margin: '0 auto' }}>
      {/* ── En-tête ── */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 20 }}>
        <div>
          <h2 style={{ margin: 0, fontSize: 18, fontWeight: 700 }}>📋 Historique des modifications</h2>
          <p style={{ margin: '4px 0 0', fontSize: 12, color: C.muted }}>
            Détail cellule par cellule disponible sur les 7 derniers jours.
          </p>
        </div>
        <button onClick={load}
          style={{ background: C.accent, color: '#fff', border: 'none', borderRadius: 7,
                   padding: '7px 16px', fontSize: 13, fontWeight: 600, cursor: 'pointer' }}>
          ↻ Actualiser
        </button>
      </div>

      {/* ── Filtres ── */}
      <div style={{ display: 'flex', gap: 12, marginBottom: 16, flexWrap: 'wrap' }}>
        <select value={filterProjet} onChange={e => setFilterProjet(e.target.value)}
          style={{ padding: '6px 10px', borderRadius: 6, border: '1px solid ' + C.border,
                   background: C.card, color: C.text, fontSize: 13 }}>
          <option value="">Tous les programmes</option>
          {projets.map(([id, nom]) => (
            <option key={id} value={id}>{nom}</option>
          ))}
        </select>

        <select value={filterSource} onChange={e => setFilterSource(e.target.value)}
          style={{ padding: '6px 10px', borderRadius: 6, border: '1px solid ' + C.border,
                   background: C.card, color: C.text, fontSize: 13 }}>
          <option value="">Toutes les sources</option>
          {Object.entries(SOURCE_META).map(([k, v]) => (
            <option key={k} value={k}>{v.label}</option>
          ))}
        </select>

        {(filterProjet || filterSource) && (
          <button onClick={() => { setFilterProjet(''); setFilterSource(''); }}
            style={{ padding: '6px 12px', borderRadius: 6, border: '1px solid ' + C.border,
                     background: 'none', color: C.muted, fontSize: 13, cursor: 'pointer' }}>
            ✕ Réinitialiser
          </button>
        )}

        <span style={{ marginLeft: 'auto', fontSize: 12, color: C.muted, alignSelf: 'center' }}>
          {filtered.length} opération{filtered.length !== 1 ? 's' : ''}
        </span>
      </div>

      {/* ── État ── */}
      {loading && (
        <div style={{ textAlign: 'center', padding: 48, color: C.muted }}>Chargement…</div>
      )}
      {error && (
        <div style={{ background: '#fef2f2', border: '1px solid #fecaca', borderRadius: 8,
                      padding: '12px 16px', color: '#dc2626', fontSize: 13 }}>
          Erreur : {error}
        </div>
      )}

      {/* ── Tableau ── */}
      {!loading && !error && (
        filtered.length === 0 ? (
          <div style={{ textAlign: 'center', padding: 48, color: C.muted, fontSize: 14 }}>
            Aucune modification enregistrée pour l'instant.
          </div>
        ) : (
          <div style={{ background: C.card, border: '1px solid ' + C.border, borderRadius: 10, overflow: 'hidden' }}>
            <table style={{ width: '100%', borderCollapse: 'collapse' }}>
              <thead>
                <tr style={{ background: C.bg }}>
                  <th style={th}>Date</th>
                  <th style={th}>Programme</th>
                  <th style={th}>Lot</th>
                  <th style={th}>Action</th>
                  <th style={th}>Source</th>
                  <th style={{ ...th, textAlign: 'right' }}>Impact</th>
                  <th style={{ ...th, textAlign: 'center' }}>Cellules</th>
                  <th style={{ ...th, textAlign: 'center' }}>Détail</th>
                </tr>
              </thead>
              <tbody>
                {filtered.map(entry => {
                  const sm = sourceMeta(entry.source);
                  const isOpen = expanded.has(entry.id);
                  const hasVerbose = entry.verbose && entry.verbose.length > 0;

                  return (
                    <React.Fragment key={entry.id}>
                      <tr style={{ background: isOpen ? C.bg : 'transparent' }}>
                        <td style={{ ...td, fontSize: 12, color: C.muted, whiteSpace: 'nowrap' }}>
                          {fmtDate(entry.created_at)}
                        </td>
                        <td style={{ ...td, fontWeight: 600 }}>
                          {entry.projet_nom || entry.projet_id || '—'}
                        </td>
                        <td style={{ ...td, color: C.muted }}>
                          {entry.lot_numero || '—'}
                        </td>
                        <td style={td}>
                          <div style={{ fontWeight: 500 }}>{entry.action_label}</div>
                          {entry.weeks_concernees && (
                            <div style={{ fontSize: 11, color: C.muted, marginTop: 2 }}>
                              {entry.weeks_concernees}
                            </div>
                          )}
                        </td>
                        <td style={td}>
                          <span style={{ background: sm.bg, color: sm.color,
                                         borderRadius: 5, padding: '2px 8px', fontSize: 11, fontWeight: 700 }}>
                            {sm.label}
                          </span>
                        </td>
                        <td style={{ ...td, textAlign: 'right', fontWeight: 700, color: deltaColor(entry.delta_total) }}>
                          {fmtEur(entry.delta_total)}
                        </td>
                        <td style={{ ...td, textAlign: 'center', color: C.muted, fontSize: 12 }}>
                          {entry.nb_cellules}
                        </td>
                        <td style={{ ...td, textAlign: 'center' }}>
                          {hasVerbose ? (
                            <button onClick={() => toggleExpand(entry.id)}
                              style={{ background: 'none', border: 'none', cursor: 'pointer',
                                       color: C.accent, fontSize: 18, lineHeight: 1 }}>
                              {isOpen ? '▲' : '▼'}
                            </button>
                          ) : (
                            <span style={{ color: C.muted, fontSize: 11 }} title="Détail expiré (> 7 jours)">
                              —
                            </span>
                          )}
                        </td>
                      </tr>

                      {/* ── Détail verbose ── */}
                      {isOpen && hasVerbose && (
                        <tr>
                          <td colSpan={8} style={{ padding: 0 }}>
                            <div style={{ background: C.bg, borderTop: '1px solid ' + C.border,
                                          borderBottom: '1px solid ' + C.border, padding: '8px 16px 12px' }}>
                              <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12 }}>
                                <thead>
                                  <tr>
                                    <th style={{ ...th, fontSize: 10, padding: '4px 8px' }}>Ligne</th>
                                    <th style={{ ...th, fontSize: 10, padding: '4px 8px' }}>Semaine</th>
                                    <th style={{ ...th, fontSize: 10, padding: '4px 8px', textAlign: 'right' }}>Avant</th>
                                    <th style={{ ...th, fontSize: 10, padding: '4px 8px', textAlign: 'right' }}>Après</th>
                                    <th style={{ ...th, fontSize: 10, padding: '4px 8px', textAlign: 'right' }}>Δ</th>
                                  </tr>
                                </thead>
                                <tbody>
                                  {entry.verbose.map((v, i) => (
                                    <tr key={i}>
                                      <td style={{ padding: '3px 8px', borderBottom: '1px solid ' + C.border, color: C.text }}>
                                        {v.rowLabel}
                                      </td>
                                      <td style={{ padding: '3px 8px', borderBottom: '1px solid ' + C.border, color: C.muted, fontFamily: 'monospace' }}>
                                        {v.weekIso}
                                      </td>
                                      <td style={{ padding: '3px 8px', borderBottom: '1px solid ' + C.border, textAlign: 'right', color: C.muted }}>
                                        {Number(v.montantAvant).toLocaleString('fr-FR', { minimumFractionDigits: 0, maximumFractionDigits: 0 })} €
                                      </td>
                                      <td style={{ padding: '3px 8px', borderBottom: '1px solid ' + C.border, textAlign: 'right', fontWeight: 600 }}>
                                        {Number(v.montantApres).toLocaleString('fr-FR', { minimumFractionDigits: 0, maximumFractionDigits: 0 })} €
                                      </td>
                                      <td style={{ padding: '3px 8px', borderBottom: '1px solid ' + C.border, textAlign: 'right',
                                                   fontWeight: 700, color: deltaColor(v.delta) }}>
                                        {fmtEur(v.delta)}
                                      </td>
                                    </tr>
                                  ))}
                                </tbody>
                              </table>
                            </div>
                          </td>
                        </tr>
                      )}
                    </React.Fragment>
                  );
                })}
              </tbody>
            </table>
          </div>
        )
      )}
    </div>
  );
}
