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

const ICONS_BASE = '/api/icons-files/';

/* Colonnes du tableau — dans l'ordre de la 2561 */
const COLS = [
  { key: 'case_2TT', code: '2TT',     label: 'Produits prêts participatifs',   color: '#7c3aed' },
  { key: 'case_2TR', code: '2TR',     label: 'Produits placement revenu fixe',  color: '#7c3aed' },
  { key: 'case_2TY', code: '2TY / AS',label: 'Pertes en capital',               color: '#dc2626', danger: true },
  { key: 'case_2BH', code: '2BH',     label: 'Base CSG/CRDS (PS prélevés)',     color: '#1d4ed8' },
  { key: 'case_2CK', code: '2CK',     label: "Crédit d'impôt prélèvement",      color: '#059669' },
];

export default function CerfaRecapTable({ annee, activeView }) {
  const [lignes,    setLignes]    = useState(null);
  const [loading,   setLoading]   = useState(true);
  const [libIcons,  setLibIcons]  = useState({});
  const [showFr,    setShowFr]    = useState(true);
  const [showWw,    setShowWw]    = useState(true);

  /* Icônes bibliothèque */
  useEffect(() => {
    api.get('/icons').then(rows => {
      const m = {};
      rows.forEach(r => { m[r.name] = r.filename; });
      setLibIcons(m);
    }).catch(() => {});
  }, []);

  useEffect(() => {
    setLoading(true);
    setLignes(null);
    const scopeParams = activeView === 'all' ? { scope: 'all' } : {};
    api.get('/taxreport/cerfa2561', { annee, ...scopeParams })
      .then(d => setLignes(d.lignes))
      .finally(() => setLoading(false));
  }, [annee, activeView]); // eslint-disable-line

  /* Filtrage FR / WW */
  const filtered = useMemo(() => {
    if (!lignes) return [];
    return lignes.filter(l => {
      const isFr = l.domiciliation === 'FR';
      return isFr ? showFr : showWw;
    });
  }, [lignes, showFr, showWw]);

  const totals = useMemo(() => (
    Object.fromEntries(
      COLS.map(c => [c.key, filtered.reduce((s, l) => s + (l[c.key] || 0), 0)])
    )
  ), [filtered]);

  /* Composant icône bibliothèque */
  const AppIcon = ({ name, size = 66, active }) => {
    const filename = libIcons[name];
    if (filename) return (
      <img
        src={ICONS_BASE + filename}
        className="app-lib-icon app-lib-icon-no-invert"
        width={size} height={size}
        aria-hidden="true"
        style={{ opacity: active ? 1 : 0.25, display: 'block', transition: 'opacity .15s' }}
      />
    );
    return (
      <span style={{
        width: size, height: size, display: 'block', borderRadius: 8,
        background: 'var(--text-muted)', opacity: active ? 0.55 : 0.15,
        transition: 'opacity .15s',
      }} />
    );
  };

  /* Détection présence de chaque type dans les données */
  const hasFr = lignes?.some(l => l.domiciliation === 'FR') ?? false;
  const hasWw = lignes?.some(l => l.domiciliation !== 'FR') ?? false;

  /* Détecter si plusieurs détenteurs distincts */
  const multiDetenteur =
    new Set((lignes ?? []).map(l => l.investisseur_id).filter(v => v != null)).size > 1;

  if (loading) {
    return (
      <div className="solde-chart-wrap" style={{ padding: '24px', marginBottom: 0 }}>
        <span className="text-muted" style={{ fontSize: 'var(--fs-sm)' }}>Chargement…</span>
      </div>
    );
  }

  if (!lignes || lignes.length === 0) {
    return (
      <div className="solde-chart-wrap" style={{ padding: '24px', marginBottom: 0 }}>
        <span className="text-muted" style={{ fontSize: 'var(--fs-sm)' }}>Aucune donnée pour {annee}.</span>
      </div>
    );
  }

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

      {/* Header */}
      <div className="solde-chart-header" style={{ marginBottom: 12 }}>
        <div className="solde-chart-info">
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap', marginBottom: 2 }}>
            <span style={{
              display: 'inline-flex', alignItems: 'center', gap: 4,
              background: 'rgba(124,58,237,0.12)', borderRadius: 5, padding: '3px 8px',
            }}>
              <span style={{ width: 7, height: 7, borderRadius: 2, background: '#7c3aed', flexShrink: 0 }} />
              <span style={{ fontSize: 13, color: '#7c3aed', fontWeight: 600 }}>Cases 2561</span>
            </span>
            <span style={{ fontSize: 13, color: 'var(--text-muted)' }}>· {annee}</span>
          </div>
          <div className="solde-chart-value" style={{ fontSize: '1.4rem' }}>
            {fmtEUR(totals.case_2TT + totals.case_2TR)}
          </div>
        </div>

        {/* Boutons filtre FR / WW */}
        <div className="solde-chart-controls">
          {hasFr && (
            <button
              title={showFr ? 'Plateformes françaises incluses' : 'Afficher les plateformes françaises'}
              onClick={() => setShowFr(v => !v)}
              style={{
                background: showFr ? 'rgba(59,130,246,0.12)' : 'none',
                border: '1px solid ' + (showFr ? 'rgba(59,130,246,0.5)' : 'transparent'),
                borderRadius: 10, padding: '5px 7px', cursor: 'pointer',
                display: 'flex', alignItems: 'center',
                transition: 'background .15s, border-color .15s',
              }}
            >
              <div style={{ background: '#fff', borderRadius: 7, lineHeight: 0 }}>
                <AppIcon name="plateforme-fr" size={44} active={showFr} />
              </div>
            </button>
          )}
          {hasWw && (
            <button
              title={showWw ? 'Plateformes étrangères incluses' : 'Afficher les plateformes étrangères'}
              onClick={() => setShowWw(v => !v)}
              style={{
                background: showWw ? 'rgba(16,185,129,0.12)' : 'none',
                border: '1px solid ' + (showWw ? 'rgba(16,185,129,0.5)' : 'transparent'),
                borderRadius: 10, padding: '5px 7px', cursor: 'pointer',
                display: 'flex', alignItems: 'center',
                transition: 'background .15s, border-color .15s',
              }}
            >
              <div style={{ background: '#fff', borderRadius: 7, lineHeight: 0 }}>
                <AppIcon name="plateforme-ww" size={44} active={showWw} />
              </div>
            </button>
          )}
        </div>
      </div>

      {filtered.length === 0 ? (
        <div style={{ padding: '20px 0', textAlign: 'center', color: 'var(--text-muted)', fontSize: 'var(--fs-sm)' }}>
          Aucune plateforme à afficher — activez au moins un filtre.
        </div>
      ) : (
        <div style={{ overflowX: 'auto' }}>
          <table className="tip-table">
            <thead>
              <tr>
                <th className="tip-th-name tip-th-name-amber">Plateforme</th>
                {COLS.map(c => (
                  <th key={c.key} className="tip-th-month" style={{ minWidth: 110 }}>
                    <span style={{ display: 'block', fontWeight: 800, letterSpacing: '.03em' }}>{c.code}</span>
                    <span style={{ display: 'block', fontSize: 10, fontWeight: 400, opacity: .85, marginTop: 1 }}>{c.label}</span>
                  </th>
                ))}
              </tr>
            </thead>
            <tbody>
              {filtered.map(l => (
                <tr key={`${l.plateforme_id}_${l.investisseur_id}`} className="tip-row-plat">
                  <td className="tip-td-name">
                    {l.plateforme_nom}
                    {multiDetenteur && l.investisseur_prenom && (
                      <span style={{ marginLeft: 6, fontSize: 'var(--fs-xs)', color: 'var(--text-muted)', fontWeight: 400 }}>
                        {l.investisseur_prenom}
                      </span>
                    )}
                  </td>
                  {COLS.map(c => {
                    const v = l[c.key] || 0;
                    return (
                      <td
                        key={c.key}
                        className="tip-td-num"
                        style={c.danger && v > 0 ? { color: '#dc2626', fontWeight: 600 } : undefined}
                      >
                        {v > 0 ? fmtEUR(v) : <span className="tip-dash">---</span>}
                      </td>
                    );
                  })}
                </tr>
              ))}
            </tbody>
            <tfoot>
              <tr className="tip-footer-total">
                <td className="tip-td-name">Total {annee}</td>
                {COLS.map(c => {
                  const v = totals[c.key] || 0;
                  return (
                    <td
                      key={c.key}
                      className="tip-td-total"
                      style={c.danger && v > 0 ? { color: '#dc2626' } : undefined}
                    >
                      {v > 0 ? fmtEUR(v) : <span className="tip-dash">---</span>}
                    </td>
                  );
                })}
              </tr>
            </tfoot>
          </table>
        </div>
      )}

      <p style={{ margin: '10px 0 0', fontSize: 11, color: 'var(--text-muted)' }}>
        ⚠ Montants indicatifs. Référez-vous à votre IFU et à la notice 2041-GFI avant toute déclaration.
      </p>
    </div>
  );
}
