import { useEffect, useMemo, useState } from 'react';
import { api } from '../api.js';
import { fmtEUR } from '../utils/format.js';

const MOIS_LONG    = ['Janvier','Février','Mars','Avril','Mai','Juin','Juillet','Août','Septembre','Octobre','Novembre','Décembre'];
const ICONS_BASE   = '/api/icons-files/';
const COLOR_DEPOT  = '#22c55e';
const COLOR_RETRAIT = '#ef4444';

function hexToRgba(hex, a) {
  if (!hex || hex.length < 7) return `rgba(0,0,0,${a})`;
  const r = parseInt(hex.slice(1,3),16), g = parseInt(hex.slice(3,5),16), b = parseInt(hex.slice(5,7),16);
  return `rgba(${r},${g},${b},${a})`;
}

function ChevronDown({ size = 10 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none"
      stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
      <path d="M6 9l6 6 6-6"/>
    </svg>
  );
}

export default function DepotsMensuelTable({ allRows, plats, expandButton }) {
  const currentYear  = new Date().getFullYear();
  const currentMonth = new Date().getMonth() + 1;

  const [annee,           setAnnee]           = useState(currentYear);
  const [inclureDepots,   setInclureDepots]   = useState(true);
  const [inclureRetraits, setInclureRetraits] = useState(false);
  const [libIcons,        setLibIcons]        = useState({});

  /* ── Toggle consolidation détenteurs ── */
  const [groupByNom, setGroupByNom] = useState(() => {
    try { return localStorage.getItem('cl_tip_group_by_nom') === 'true'; } catch { return false; }
  });
  const toggleGroupByNom = () => {
    setGroupByNom(v => {
      const next = !v;
      try { localStorage.setItem('cl_tip_group_by_nom', String(next)); } catch {}
      return next;
    });
  };

  /* Icones bibliotheque */
  useEffect(() => {
    api.get('/icons').then(rows => {
      const m = {};
      rows.forEach(r => { m[r.name] = r.filename; });
      setLibIcons(m);
    }).catch(() => {});
  }, []);

  const AppIcon = ({ name, size = 28, active = false }) => {
    const filename = libIcons[name];
    if (filename) return (
      <img src={ICONS_BASE + filename} className="app-lib-icon" width={size} height={size}
        aria-hidden="true"
        style={{ opacity: active ? 1 : 0.35, display: 'block', transition: 'opacity .15s' }} />
    );
    return <span style={{ width: size, height: size, display: 'block', borderRadius: 4,
      background: 'var(--text-muted)', opacity: active ? 0.55 : 0.2, transition: 'opacity .15s' }} />;
  };

  /* Annees disponibles */
  const availableYears = useMemo(() => {
    const set = new Set(allRows.map(r => r.date_operation?.slice(0, 4)).filter(Boolean));
    return [...set].map(Number).sort((a, b) => a - b);
  }, [allRows]);

  /* Fenetre selecteur */
  const [windowStart, setWindowStart] = useState(() => {
    const idx = availableYears.indexOf(currentYear);
    const safe = idx >= 0 ? idx : availableYears.length - 1;
    return Math.max(0, Math.min(Math.max(0, availableYears.length - 3), safe - 1));
  });
  const visibleYears = availableYears.length ? availableYears.slice(windowStart, windowStart + 3) : [annee];
  const canPrev = windowStart > 0;
  const canNext = windowStart + 3 < availableYears.length;

  /* Grille par plateforme x mois */
  const { grid, stats, multiDetenteur } = useMemo(() => {
    const anneeStr = String(annee);
    const rows = allRows.filter(r => r.date_operation?.slice(0, 4) === anneeStr);

    const byPlat = {};
    for (const r of rows) {
      const pid = r.plateforme_id;
      if (!byPlat[pid]) {
        byPlat[pid] = {
          id: pid,
          nom: r.plateforme_nom || '—',
          investisseur_id: r.investisseur_id ?? null,
          detenteur_nom: r.plateforme_detenteur_nom || null,
          depots:   Array(12).fill(0),
          retraits: Array(12).fill(0),
        };
      }
      const mi = parseInt(r.date_operation.slice(5, 7), 10) - 1;
      if (r.type === 'depot')   byPlat[pid].depots[mi]   += r.montant || 0;
      if (r.type === 'retrait') byPlat[pid].retraits[mi] += r.montant || 0;
    }

    const allPlats = Object.values(byPlat);
    const multi = new Set(allPlats.map(p => p.investisseur_id).filter(v => v != null)).size > 1;

    // Consolidation par nom si demandée
    let consolidated;
    if (groupByNom && multi) {
      const byNom = {};
      for (const p of allPlats) {
        if (!byNom[p.nom]) {
          byNom[p.nom] = { id: p.nom, nom: p.nom, investisseur_id: null, detenteur_nom: null,
            depots: [...p.depots], retraits: [...p.retraits] };
        } else {
          for (let i = 0; i < 12; i++) {
            byNom[p.nom].depots[i]   += p.depots[i];
            byNom[p.nom].retraits[i] += p.retraits[i];
          }
        }
      }
      consolidated = Object.values(byNom);
    } else {
      consolidated = allPlats;
    }

    const cellValue = (p, mi) => {
      const d  = inclureDepots   ? p.depots[mi]   : 0;
      const rv = inclureRetraits ? p.retraits[mi] : 0;
      if (inclureDepots && inclureRetraits) return d - rv;
      return d + rv;
    };

    const grid = consolidated
      .map(p => ({ ...p, months: Array.from({ length: 12 }, (_, i) => cellValue(p, i)) }))
      .filter(p => p.months.some(v => v !== 0))
      .sort((a, b) => b.depots.reduce((s, v) => s + v, 0) - a.depots.reduce((s, v) => s + v, 0));

    const monthTotals = Array.from({ length: 12 }, (_, i) =>
      grid.reduce((s, row) => s + row.months[i], 0));
    const grandTotal  = monthTotals.reduce((s, v) => s + v, 0);
    const platTotals  = grid.map(row => row.months.reduce((s, v) => s + v, 0));
    const nonZero     = monthTotals.filter(v => v !== 0);
    const globalMoyenne = nonZero.length ? nonZero.reduce((s, v) => s + v, 0) / nonZero.length : 0;

    return { grid, stats: { monthTotals, grandTotal, platTotals, globalMoyenne }, multiDetenteur: multi };
  }, [allRows, annee, inclureDepots, inclureRetraits, groupByNom]);

  return (
    <div className="solde-chart-wrap" style={{ padding: '24px 24px 16px', marginBottom: 24 }}>

      <div className="solde-chart-header">
        <div className="solde-chart-info">
          <div style={{ display:'flex', alignItems:'center', gap:5, flexWrap:'wrap', marginBottom:2 }}>
            {inclureDepots && (
              <span style={{ display:'inline-flex', alignItems:'center', gap:4,
                background: hexToRgba(COLOR_DEPOT, 0.12), borderRadius:5, padding:'3px 8px' }}>
                <span style={{ width:7, height:7, borderRadius:2, background: COLOR_DEPOT, flexShrink:0 }}/>
                <span style={{ fontSize:13, color: COLOR_DEPOT, fontWeight:600 }}>Depots</span>
              </span>
            )}
            {inclureRetraits && (
              <span style={{ display:'inline-flex', alignItems:'center', gap:4,
                background: hexToRgba(COLOR_RETRAIT, 0.12), borderRadius:5, padding:'3px 8px' }}>
                <span style={{ width:7, height:7, borderRadius:2, background: COLOR_RETRAIT, flexShrink:0 }}/>
                <span style={{ fontSize:13, color: COLOR_RETRAIT, fontWeight:600 }}>Retraits</span>
              </span>
            )}
            {!inclureDepots && !inclureRetraits && (
              <span style={{ fontSize:13, color:'var(--text-muted)' }}>---</span>
            )}
            <span style={{ fontSize:13, color:'var(--text-muted)' }}>. {annee}</span>
          </div>
          <div className="solde-chart-value">{fmtEUR(stats.grandTotal)}</div>
        </div>

        <div className="solde-chart-controls">
          <button
            title={inclureDepots ? 'Depots inclus' : 'Inclure les depots'}
            onClick={() => setInclureDepots(v => !v)}
            style={{ background: inclureDepots ? hexToRgba(COLOR_DEPOT, 0.13) : 'none',
              border: '1px solid ' + (inclureDepots ? COLOR_DEPOT : 'transparent'),
              borderRadius:8, padding:'4px 6px', cursor:'pointer', display:'flex', alignItems:'center',
              transition:'background .15s,border-color .15s', marginRight:2 }}>
            <AppIcon name="depot" active={inclureDepots} />
          </button>
          <button
            title={inclureRetraits ? 'Retraits inclus' : 'Inclure les retraits'}
            onClick={() => setInclureRetraits(v => !v)}
            style={{ background: inclureRetraits ? hexToRgba(COLOR_RETRAIT, 0.13) : 'none',
              border: '1px solid ' + (inclureRetraits ? COLOR_RETRAIT : 'transparent'),
              borderRadius:8, padding:'4px 6px', cursor:'pointer', display:'flex', alignItems:'center',
              transition:'background .15s,border-color .15s', marginRight:2 }}>
            <AppIcon name="retrait" active={inclureRetraits} />
          </button>

          <div className="solde-chart-ranges">
            <button className="solde-range-btn"
              onClick={() => setWindowStart(w => Math.max(0, w - 1))}
              disabled={!canPrev} style={{ opacity: canPrev ? 1 : 0.3 }}>&#x2039;</button>
            {visibleYears.map(y => (
              <button key={y}
                className={'solde-range-btn' + (annee === y ? ' active' : '')}
                onClick={() => setAnnee(y)}>
                {y}
              </button>
            ))}
            <button className="solde-range-btn"
              onClick={() => setWindowStart(w => Math.min(Math.max(0, availableYears.length - 3), w + 1))}
              disabled={!canNext} style={{ opacity: canNext ? 1 : 0.3 }}>&#x203a;</button>
            <button
              className={'solde-range-btn' + (annee === currentYear ? ' active' : '')}
              onClick={() => setAnnee(currentYear)}>
              TOUT
            </button>
            {expandButton}
          </div>
        </div>
      </div>

      {grid.length === 0 ? (
        <div style={{ marginTop: 20, color: 'var(--text-muted)', fontSize: 'var(--fs-sm)', padding: '24px 0', textAlign: 'center' }}>
          {!inclureDepots && !inclureRetraits
            ? 'Selectionne au moins un type de mouvement.'
            : 'Aucun mouvement pour ' + annee + '.'}
        </div>
      ) : (
        <div style={{ overflowX: 'auto', marginTop: 20, position: 'relative', zIndex: 0 }}>
          <table className="tip-table">
            <thead>
              <tr>
                <th className="tip-th-empty" />
                <th className="tip-th-year" colSpan={12}>{annee}</th>
                <th className="tip-th-empty" />
                <th className="tip-th-empty" />
              </tr>
              <tr>
                <th className="tip-th-name tip-th-name-amber">
                  <span style={{ display:'flex', alignItems:'center', gap:6 }}>
                    Plateforme
                    {multiDetenteur && (
                      <button
                        onClick={() => toggleGroupByNom()}
                        title={groupByNom ? 'Vue consolidée — cliquer pour détailler par détenteur' : 'Vue détaillée — cliquer pour consolider par plateforme'}
                        style={{
                          display:'inline-flex', alignItems:'center', gap:3,
                          background:'rgba(255,255,255,0.15)', border:'1px solid rgba(255,255,255,0.3)',
                          borderRadius:4, padding:'2px 5px', cursor:'pointer',
                          fontSize:10, fontWeight:600, color:'#fff', letterSpacing:'.03em',
                          lineHeight:1.4, whiteSpace:'nowrap', transition:'background .15s',
                        }}>
                        {groupByNom ? 'Consolidé' : 'Détaillé'}
                        <span style={{ display:'inline-flex', transition:'transform .2s', transform: groupByNom ? 'rotate(180deg)' : 'rotate(0deg)' }}>
                          <ChevronDown size={9} />
                        </span>
                      </button>
                    )}
                  </span>
                </th>
                {MOIS_LONG.map((m, i) => (
                  <th key={m}
                    className={'tip-th-month' + (annee === currentYear && i === currentMonth - 1 ? ' tip-th-month-current' : '')}>
                    {m}
                  </th>
                ))}
                <th className="tip-th-total">Total</th>
                <th className="tip-th-avg">Moy. mensuelle</th>
              </tr>
            </thead>
            <tbody>
              {grid.map((plat, pi) => (
                <tr key={plat.id} className="tip-row-plat">
                  <td className="tip-td-name">
                    {plat.nom}
                    {!groupByNom && multiDetenteur && plat.detenteur_nom && (
                      <span style={{ marginLeft: 6, fontSize: 'var(--fs-xs)', color: 'var(--text-muted)', fontWeight: 400 }}>
                        {plat.detenteur_nom}
                      </span>
                    )}
                  </td>
                  {plat.months.map((v, mi) => (
                    <td key={mi}
                      className={'tip-td-num' + (annee === currentYear && mi === currentMonth - 1 ? ' tip-col-current' : '')}
                      style={v < 0 ? { color: COLOR_RETRAIT } : undefined}>
                      {v !== 0 ? fmtEUR(v) : <span className="tip-dash">---</span>}
                    </td>
                  ))}
                  <td className="tip-td-total" style={stats.platTotals[pi] < 0 ? { color: COLOR_RETRAIT } : undefined}>
                    {stats.platTotals[pi] !== 0 ? fmtEUR(stats.platTotals[pi]) : <span className="tip-dash">---</span>}
                  </td>
                  <td className="tip-td-avg">
                    {stats.platTotals[pi] !== 0 ? fmtEUR(stats.platTotals[pi] / 12) : <span className="tip-dash">---</span>}
                  </td>
                </tr>
              ))}
            </tbody>
            <tfoot>
              <tr className="tip-footer-total">
                <td className="tip-td-name">Toutes les plateformes</td>
                {stats.monthTotals.map((v, i) => (
                  <td key={i}
                    className={'tip-td-num' + (annee === currentYear && i === currentMonth - 1 ? ' tip-col-current' : '')}
                    style={v < 0 ? { color: COLOR_RETRAIT } : undefined}>
                    {v !== 0 ? fmtEUR(v) : <span className="tip-dash">---</span>}
                  </td>
                ))}
                <td className="tip-td-total" style={stats.grandTotal < 0 ? { color: COLOR_RETRAIT } : undefined}>
                  {fmtEUR(stats.grandTotal)}
                </td>
                <td className="tip-td-avg">
                  {stats.globalMoyenne !== 0 ? fmtEUR(stats.globalMoyenne) : <span className="tip-dash">---</span>}
                </td>
              </tr>
            </tfoot>
          </table>
        </div>
      )}
    </div>
  );
}
