import { useMemo, useState, useRef } from 'react';
import { useInteretsChart } from '../context/InteretsChartContext.jsx';

function fmtTotal(v) {
  return v.toLocaleString('fr-FR',{minimumFractionDigits:2,maximumFractionDigits:2})+' €';
}
function fmtCenter(v) {
  if (!v||v===0) return '—';
  return v.toLocaleString('fr-FR',{minimumFractionDigits:2,maximumFractionDigits:2})+' €';
}

/* ── Helpers SVG ──────────────────────────────────────────────── */
function polar(cx,cy,r,deg) {
  const rad=(deg-90)*Math.PI/180;
  return {x:cx+r*Math.cos(rad), y:cy+r*Math.sin(rad)};
}

function roundedArcPath(cx, cy, outerR, innerR, startDeg, endDeg) {
  const span = endDeg - startDeg;
  if (span < 0.1) return '';
  const f = n => n.toFixed(2);

  if (span >= 359.9) {
    const o0=polar(cx,cy,outerR,0),   o1=polar(cx,cy,outerR,180);
    const i0=polar(cx,cy,innerR,0),   i1=polar(cx,cy,innerR,180);
    return [
      `M${f(o0.x)} ${f(o0.y)} A${outerR} ${outerR} 0 1 1 ${f(o1.x)} ${f(o1.y)}`,
      `A${outerR} ${outerR} 0 1 1 ${f(o0.x)} ${f(o0.y)} Z`,
      `M${f(i0.x)} ${f(i0.y)} A${innerR} ${innerR} 0 1 1 ${f(i1.x)} ${f(i1.y)}`,
      `A${innerR} ${innerR} 0 1 1 ${f(i0.x)} ${f(i0.y)} Z`,
    ].join(' ');
  }

  const capR = (outerR - innerR) / 2;
  const lg = span > 180 ? 1 : 0;
  const oS=polar(cx,cy,outerR,startDeg), oE=polar(cx,cy,outerR,endDeg);
  const iS=polar(cx,cy,innerR,startDeg), iE=polar(cx,cy,innerR,endDeg);

  return [
    `M${f(oS.x)} ${f(oS.y)}`,
    `A${outerR} ${outerR} 0 ${lg} 1 ${f(oE.x)} ${f(oE.y)}`,
    `A${capR} ${capR} 0 0 1 ${f(iE.x)} ${f(iE.y)}`,
    `A${innerR} ${innerR} 0 ${lg} 0 ${f(iS.x)} ${f(iS.y)}`,
    `A${capR} ${capR} 0 0 0 ${f(oS.x)} ${f(oS.y)}`,
    'Z',
  ].join(' ');
}

/* ── Dimensions donut ─────────────────────────────────────────── */
const CX=120, CY=120;
const OUTER_R=108, INNER_R=72;

export default function InteretsDonutChart() {
  const {
    annee,
    inclureInterets, setInclureInterets,
    inclureCapital,  setInclureCapital,
    inclureCashback, setInclureCashback,
    selectedMonth, setSelectedMonth,
    showActual, showProjected,
    selectActualOnly, selectProjectedOnly, setActualProjected,
    months,
    modeGlobal,
    selectedYear, setSelectedYear,
    years,
    chartInterets, chartCapital, chartCashback,
    netMode,
  } = useInteretsChart();

  const [hoveredArcIdx,  setHoveredArcIdx]  = useState(null);
  const [hoveredLegIdx,  setHoveredLegIdx]  = useState(null);
  const [centerHovered,  setCenterHovered]  = useState(false);

  /* ── Mémoire de filtrage ─────────────────────────────────────── */
  const prevStateRef = useRef(null);
  const [hasPrev, setHasPrev] = useState(false);

  const activeCount = [inclureCapital, inclureCashback, inclureInterets].filter(Boolean).length;

  /* ── Construire un item donut ────────────────────────────────── */
  const makeItem = (label, color, opacity, actualAmt, projectedAmt) => ({
    label, color, opacity,
    value: actualAmt + projectedAmt,
    actualAmt, projectedAmt,
  });

  /* ── Source de données — ordre fixe : Intérêts → Capital → Cashback ── */
  const donutData = useMemo(() => {
    if (activeCount===0) return [];

    if (modeGlobal) {
      const src = selectedYear !== null ? years.find(y => y.y === selectedYear) : null;
      const sumA = key => showActual    ? (src ? (src[key]||0) : years.reduce((s,y) => s+(y[key]||0), 0)) : 0;
      const sumP = key => showProjected ? (src ? (src[key]||0) : years.reduce((s,y) => s+(y[key]||0), 0)) : 0;

      if (activeCount===1) {
        if (inclureInterets) {
          const actual=sumA('interetsAmt'), proj=sumP('interetsProjAmt'), s=[];
          if(actual>0) s.push(makeItem('Reçu',    chartInterets, 0.88, actual, 0));
          if(proj  >0) s.push(makeItem('Projeté', chartInterets, 0.30, proj,   0));
          return s;
        }
        if (inclureCapital) {
          const actual=sumA('capitalAmt'), proj=sumP('capitalProjAmt'), s=[];
          if(actual>0) s.push(makeItem('Reçu',    chartCapital, 0.88, actual, 0));
          if(proj  >0) s.push(makeItem('Projeté', chartCapital, 0.30, proj,   0));
          return s;
        }
        if (inclureCashback) {
          const v=sumA('cashbackAmt');
          return v>0?[makeItem('Reçu', chartCashback, 0.88, v, 0)]:[];
        }
      }
      // Multi-types — ordre : Intérêts → Capital → Cashback
      const s=[];
      if(inclureInterets){
        const a=sumA('interetsAmt'), p=sumP('interetsProjAmt');
        if(a+p>0) s.push(makeItem(netMode?'Intérêts nets':'Intérêts bruts', chartInterets, 0.88, a, p));
      }
      if(inclureCapital){
        const a=sumA('capitalAmt'), p=sumP('capitalProjAmt');
        if(a+p>0) s.push(makeItem('Capital', chartCapital, 0.88, a, p));
      }
      if(inclureCashback){
        const a=sumA('cashbackAmt');
        if(a>0) s.push(makeItem('Cashback', chartCashback, 0.88, a, 0));
      }
      return s;
    }

    // Mode mensuel
    const src=selectedMonth!==null?months[selectedMonth]:null;
    const sumA=key=>showActual    ?(src?(src[key]||0):months.reduce((s,m)=>s+(m[key]||0),0)):0;
    const sumP=key=>showProjected ?(src?(src[key]||0):months.reduce((s,m)=>s+(m[key]||0),0)):0;

    if (activeCount===1) {
      if (inclureInterets) {
        const actual=sumA('interetsAmt'), proj=sumP('interetsProjAmt'), s=[];
        if(actual>0) s.push(makeItem('Reçu',    chartInterets, 0.88, actual, 0));
        if(proj  >0) s.push(makeItem('Projeté', chartInterets, 0.30, proj,   0));
        return s;
      }
      if (inclureCapital) {
        const actual=sumA('capitalAmt'), proj=sumP('capitalProjAmt'), s=[];
        if(actual>0) s.push(makeItem('Reçu',    chartCapital, 0.88, actual, 0));
        if(proj  >0) s.push(makeItem('Projeté', chartCapital, 0.30, proj,   0));
        return s;
      }
      if (inclureCashback) {
        const v=sumA('cashbackAmt');
        return v>0?[makeItem('Reçu', chartCashback, 0.88, v, 0)]:[];
      }
    }
    // Multi-types — ordre : Intérêts → Capital → Cashback
    const s=[];
    if(inclureInterets){
      const a=sumA('interetsAmt'), p=sumP('interetsProjAmt');
      if(a+p>0) s.push(makeItem(netMode?'Intérêts nets':'Intérêts bruts', chartInterets, 0.88, a, p));
    }
    if(inclureCapital){
      const a=sumA('capitalAmt'), p=sumP('capitalProjAmt');
      if(a+p>0) s.push(makeItem('Capital', chartCapital, 0.88, a, p));
    }
    if(inclureCashback){
      const a=sumA('cashbackAmt');
      if(a>0) s.push(makeItem('Cashback', chartCashback, 0.88, a, 0));
    }
    return s;
  },[months,selectedMonth,inclureCapital,inclureCashback,inclureInterets,
     showActual,showProjected,chartCapital,chartCashback,chartInterets,
     modeGlobal,years,selectedYear,activeCount]);

  const total=donutData.reduce((s,d)=>s+d.value,0);
  const GAP = donutData.length <= 1 ? 0 : 4;

  const arcs = useMemo(() => {
    const out=[]; let cur=0;
    donutData.forEach(d => {
      const sweep = total > 0 ? (d.value / total) * 360 : 0;
      const s = cur + GAP/2, e = cur + sweep - GAP/2;
      if (e - s > 0.1) out.push({...d, startDeg:s, endDeg:e});
      cur += sweep;
    });
    return out;
  },[donutData,total,GAP]);

  /* ── Clic sur un quartier ou une ligne de légende ───────────── */
  const handleArcClick = (item) => {
    prevStateRef.current = {
      inclureInterets, inclureCapital, inclureCashback,
      showActual, showProjected,
    };
    setHasPrev(true);

    if (activeCount > 1) {
      setInclureCapital(item.label === 'Capital');
      setInclureCashback(item.label === 'Cashback');
      setInclureInterets(item.label === 'Intérêts nets' || item.label === 'Intérêts bruts');
    } else {
      if (item.label === 'Reçu')    selectActualOnly();
      if (item.label === 'Projeté') selectProjectedOnly();
    }
  };

  /* ── Retour arrière via clic centre ──────────────────────────── */
  const handleCenterClick = () => {
    if (!hasPrev || !prevStateRef.current) return;
    const ps = prevStateRef.current;
    setInclureCapital(ps.inclureCapital);
    setInclureCashback(ps.inclureCashback);
    setInclureInterets(ps.inclureInterets);
    setActualProjected(ps.showActual, ps.showProjected);
    prevStateRef.current = null;
    setHasPrev(false);
  };

  /* ── Tooltip positionné sur le point extérieur de l'arc ────── */
  const tooltipArc = hoveredArcIdx !== null ? arcs[hoveredArcIdx] : null;
  const tooltipPos = tooltipArc ? (() => {
    const midAngle = (tooltipArc.startDeg + tooltipArc.endDeg) / 2;
    const tipPt = polar(CX, CY, OUTER_R + 12, midAngle);
    return {
      pctX: (tipPt.x / 240) * 100,
      pctY: (tipPt.y / 240) * 100,
      onRight:  tipPt.x >= CX,
      onBottom: tipPt.y >= CY,
    };
  })() : null;

  /* ── Sous-détail reçu/projeté pour la légende ───────────────── */
  const getLegendDetail = (d) => {
    if (activeCount <= 1) return null;
    if (d.actualAmt > 0 && d.projectedAmt > 0) {
      if (d.label !== 'Intérêts nets' && d.label !== 'Intérêts bruts' && d.label !== 'Capital') return null;
      return `dont ${fmtTotal(d.actualAmt)} reçus · ${fmtTotal(d.projectedAmt)} projetés`;
    }
    return null;
  };

  /* ── Labels / sélection ──────────────────────────────────────── */
  const centerLabel = modeGlobal
    ? (selectedYear !== null ? String(selectedYear) : 'Total')
    : (selectedMonth !== null ? months[selectedMonth].label : 'Total');

  const headerSub = modeGlobal
    ? (selectedYear !== null ? String(selectedYear) : 'Toutes les années')
    : (selectedMonth !== null ? `${months[selectedMonth].labelLong} ${annee}` : String(annee));

  const hasSelection = modeGlobal ? selectedYear !== null : selectedMonth !== null;

  const clearSelection = () => {
    if (modeGlobal) setSelectedYear(null);
    else setSelectedMonth(null);
  };

  return (
    <div className="solde-chart-wrap" style={{
      padding:'20px 20px 16px',
      height:'100%', boxSizing:'border-box',
      display:'flex', flexDirection:'column',
    }}>

      {/* ── SVG donut ── */}
      <div style={{flex:1,display:'flex',alignItems:'center',justifyContent:'center',minHeight:0,padding:'4px 0'}}>
        <div style={{position:'relative',width:'100%',maxWidth:260}}
          onMouseLeave={()=>{ setHoveredArcIdx(null); setCenterHovered(false); }}
        >
          <svg viewBox="0 0 240 240" style={{width:'100%',height:'auto',display:'block'}}>
            {/* Anneau de fond */}
            <circle cx={CX} cy={CY} r={(OUTER_R+INNER_R)/2} fill="none"
              stroke="var(--border)" strokeWidth={OUTER_R-INNER_R} opacity={0.18}/>

            {/* Segments */}
            {total>0 && arcs.map((arc,i)=>(
              <path key={i}
                d={roundedArcPath(CX,CY,OUTER_R,INNER_R,arc.startDeg,arc.endDeg)}
                fill={arc.color}
                fillRule={arc.endDeg-arc.startDeg>=359.9?'evenodd':undefined}
                opacity={hoveredArcIdx===i
                  ? Math.min(1,(arc.opacity??0.88)+0.12)
                  : (arc.opacity??0.88)}
                style={{cursor:'pointer',transition:'opacity .12s'}}
                onMouseEnter={()=>setHoveredArcIdx(i)}
                onClick={()=>handleArcClick(arc)}
              />
            ))}

            {/* Zone cliquable centre */}
            <circle cx={CX} cy={CY} r={INNER_R - 2}
              fill={centerHovered && hasPrev ? 'var(--primary)' : 'transparent'}
              fillOpacity={centerHovered && hasPrev ? 0.07 : 0}
              style={{ cursor: hasPrev ? 'pointer' : 'default', transition:'fill-opacity .15s' }}
              onMouseEnter={()=>setCenterHovered(true)}
              onMouseLeave={()=>setCenterHovered(false)}
              onClick={handleCenterClick}
            />

            {/* Indicateur retour arrière */}
            {hasPrev && (
              <text x={CX} y={CY-22} textAnchor="middle" fontSize="13"
                fill="var(--primary)" fontFamily="system-ui,sans-serif"
                opacity={centerHovered ? 1 : 0.55}
                style={{transition:'opacity .15s', pointerEvents:'none'}}>
                ↩
              </text>
            )}

            {/* Texte central */}
            <text x={CX} y={hasPrev ? CY-4 : CY-9}
              textAnchor="middle" fontSize="12"
              fill={hasPrev && centerHovered ? 'var(--primary)' : 'var(--text-muted)'}
              fontFamily="system-ui,sans-serif" fontWeight="400"
              style={{transition:'fill .15s', pointerEvents:'none'}}>
              {centerLabel}
            </text>
            <text x={CX} y={hasPrev ? CY+14 : CY+13}
              textAnchor="middle" fontSize="18"
              fill={hasPrev && centerHovered ? 'var(--primary)' : 'var(--text)'}
              fontWeight="700" fontFamily="system-ui,sans-serif"
              style={{transition:'fill .15s', pointerEvents:'none'}}>
              {fmtCenter(total)}
            </text>
          </svg>

          {/* ── Tooltip arc ── */}
          {tooltipArc && tooltipPos && (
            <div style={{
              position:'absolute',
              ...(tooltipPos.onRight
                ? { left:`${tooltipPos.pctX}%`, transform:'translateX(8px)' }
                : { right:`${100-tooltipPos.pctX}%`, transform:'translateX(-8px)' }),
              ...(tooltipPos.onBottom
                ? { top:`${tooltipPos.pctY}%` }
                : { bottom:`${100-tooltipPos.pctY}%` }),
              pointerEvents:'none', zIndex:30,
            }}>
              <div className="sg-tooltip">
                <span className="sg-tooltip-date" style={{display:'flex',alignItems:'center',gap:6}}>
                  <span style={{display:'inline-block',width:8,height:8,borderRadius:2,
                    background:tooltipArc.color,opacity:tooltipArc.opacity??0.88,flexShrink:0}}/>
                  {tooltipArc.label}
                </span>
                <span style={{fontSize:'var(--fs-sm)',color:'var(--text)',fontWeight:700}}>
                  {fmtTotal(tooltipArc.value)}
                </span>
                <span style={{fontSize:'var(--fs-xs)',color:'var(--text-muted)'}}>
                  {total>0 ? ((tooltipArc.value/total)*100).toFixed(1)+' %' : '—'}
                </span>
                {(activeCount > 1 || tooltipArc.label === 'Reçu' || tooltipArc.label === 'Projeté') && (
                  <span style={{
                    fontSize:'var(--fs-xs)',color:'var(--text-muted)',opacity:0.6,
                    marginTop:2,borderTop:'1px solid var(--border)',paddingTop:4,
                  }}>
                    Cliquer pour {activeCount > 1 ? 'isoler' : 'sélectionner'}
                  </span>
                )}
              </div>
            </div>
          )}

          {/* ── Tooltip centre ── */}
          {centerHovered && hasPrev && (
            <div style={{
              position:'absolute', left:'50%', top:'50%',
              transform:'translate(-50%, calc(-100% - 10px))',
              pointerEvents:'none', zIndex:30,
            }}>
              <div className="sg-tooltip" style={{textAlign:'center'}}>
                <span style={{fontSize:'var(--fs-xs)',color:'var(--primary)',fontWeight:600}}>
                  ↩ Restaurer le filtrage précédent
                </span>
              </div>
            </div>
          )}
        </div>
      </div>

      {/* ── Légende ── */}
      <div style={{marginTop:4}}>
        <div style={{
          display:'flex', alignItems:'center', justifyContent:'space-between',
          marginBottom:10, paddingBottom:10,
          borderBottom:'1px solid var(--border)',
        }}>
          <span style={{fontSize:'var(--fs-sm)',fontWeight:600,color:'var(--text)'}}>Répartition</span>
          <span
            style={{
              fontSize:'var(--fs-xs)',
              color:hasSelection?'var(--primary)':'var(--text-muted)',
              cursor:hasSelection?'pointer':'default',
              display:'inline-flex', alignItems:'center', gap:4,
            }}
            onClick={hasSelection?()=>clearSelection():undefined}
            title={hasSelection?'Revenir à la vue globale':undefined}
          >
            {headerSub}
            {hasSelection&&<span style={{fontSize:11,opacity:0.7}}>×</span>}
          </span>
        </div>

        {donutData.length===0 && (
          <div style={{fontSize:'var(--fs-xs)',color:'var(--text-muted)',textAlign:'center',padding:'10px 0'}}>
            Aucun type sélectionné
          </div>
        )}

        {donutData.map((d,i)=>{
          const detail = getLegendDetail(d);
          const isClickable = activeCount > 1 || d.label === 'Reçu' || d.label === 'Projeté';
          const isHov = hoveredLegIdx === i;
          return (
            <div key={i}
              onClick={isClickable ? ()=>handleArcClick(d) : undefined}
              onMouseEnter={isClickable ? ()=>setHoveredLegIdx(i) : undefined}
              onMouseLeave={isClickable ? ()=>setHoveredLegIdx(null) : undefined}
              style={{
                display:'flex', alignItems:'center', gap:8,
                padding:'7px 6px',
                marginLeft:-6, marginRight:-6,
                borderTop: i>0 ? '1px solid var(--border)' : 'none',
                cursor: isClickable ? 'pointer' : 'default',
                borderRadius:6,
                background: isHov ? 'var(--surface-2)' : 'transparent',
                transition:'background .12s',
              }}
            >
              <span style={{
                width:10,height:10,borderRadius:2,flexShrink:0,
                background:d.color,opacity:d.opacity??0.88,
              }}/>
              <div style={{flex:1,minWidth:0,display:'flex',alignItems:'baseline',gap:6,flexWrap:'wrap'}}>
                <span style={{fontSize:'var(--fs-xs)',color:'var(--text-muted)',fontWeight:400,whiteSpace:'nowrap'}}>
                  {d.label}
                </span>
                <span style={{fontSize:'var(--fs-sm)',color:'var(--text)',fontWeight:700,whiteSpace:'nowrap'}}>
                  {fmtTotal(d.value)}
                </span>
                {detail && (
                  <span style={{fontSize:11,color:'var(--text-muted)',opacity:0.8,lineHeight:1.3}}>
                    {detail}
                  </span>
                )}
              </div>
              <span style={{fontSize:'var(--fs-xs)',color:'var(--text)',fontWeight:500,flexShrink:0,minWidth:38,textAlign:'right'}}>
                {total>0?((d.value/total)*100).toFixed(1)+' %':'—'}
              </span>
            </div>
          );
        })}


      </div>

    </div>
  );
}
