{% extends 'base.html' %}
{% set active = 'reports' %}
{% block page_title %}Report{% endblock %}
{% block header_title %}Report{% endblock %}

{% block topbar_extra %}
<select class="form-select" id="rYear" onchange="loadAll()" style="min-width:100px"></select>
{% endblock %}

{% block content %}
<div class="tab-nav">
  <button class="tab-btn active" onclick="switchTab('annuale')">📊 Annuale</button>
  <button class="tab-btn"        onclick="switchTab('tendenze')">📈 Tendenze</button>
  <button class="tab-btn"        onclick="switchTab('confronto')">⚖️ Anno su anno</button>
  <button class="tab-btn"        onclick="switchTab('topspese')">🏆 Top spese</button>
</div>

<!-- ── TAB: Annuale ──────────────────────────────────── -->
<div class="tab-pane active" id="tab-annuale">
  <div style="display:grid;grid-template-columns:repeat(4,1fr);gap:14px;margin-bottom:18px">
    <div class="stat-card"><div class="stat-icon" style="background:#d1fae5">💚</div>
      <div><div class="stat-label">Entrate</div><div class="stat-value amt-in" id="a-in">—</div></div></div>
    <div class="stat-card"><div class="stat-icon" style="background:#fee2e2">❤️</div>
      <div><div class="stat-label">Uscite</div><div class="stat-value amt-out" id="a-out">—</div></div></div>
    <div class="stat-card"><div class="stat-icon" style="background:#e0e7ff">💼</div>
      <div><div class="stat-label">Saldo annuale</div><div class="stat-value" id="a-bal">—</div></div></div>
    <div class="stat-card"><div class="stat-icon" style="background:#fef3c7">⭐</div>
      <div><div class="stat-label">Media mensile</div><div class="stat-value" id="a-avg">—</div></div></div>
  </div>

  <div class="chart-card" style="margin-bottom:16px">
    <h6>Entrate e Uscite per mese</h6>
    <canvas id="annualChart" height="120"></canvas>
  </div>

  <div style="display:grid;grid-template-columns:1.2fr 1fr;gap:16px">
    <div class="chart-card" style="padding:0;overflow:hidden">
      <div style="padding:14px 18px 6px"><h6 style="margin-bottom:0">Riepilogo mensile</h6></div>
      <table class="data-table">
        <thead><tr>
          <th>Mese</th><th style="text-align:right">Entrate</th>
          <th style="text-align:right">Uscite</th><th style="text-align:right">Saldo</th>
        </tr></thead>
        <tbody id="monthBody"></tbody>
        <tfoot id="monthFoot" style="background:#f8fafc;font-weight:700"></tfoot>
      </table>
    </div>
    <div class="chart-card">
      <h6>Uscite per categoria</h6>
      <canvas id="annualCatChart" height="220"></canvas>
      <div id="catLegend" style="margin-top:12px;display:flex;flex-direction:column;gap:5px"></div>
    </div>
  </div>
</div>

<!-- ── TAB: Tendenze ─────────────────────────────────── -->
<div class="tab-pane" id="tab-tendenze">
  <p style="color:var(--muted);font-size:.85rem;margin-bottom:14px">Media mensile per categoria negli ultimi 12 mesi.</p>
  <div class="chart-card" style="margin-bottom:16px">
    <h6>Trend uscite per categoria (12 mesi)</h6>
    <canvas id="trendLineChart" height="150"></canvas>
  </div>
  <div class="chart-card" style="padding:0;overflow:hidden">
    <div style="padding:14px 18px 6px"><h6 style="margin-bottom:0">Medie mensili per categoria</h6></div>
    <table class="data-table">
      <thead><tr>
        <th>Categoria</th><th style="text-align:right">Media/mese</th>
        <th style="text-align:right">Totale 12m</th><th style="text-align:right">Tendenza</th>
      </tr></thead>
      <tbody id="trendsBody"></tbody>
    </table>
  </div>
</div>

<!-- ── TAB: Confronto ────────────────────────────────── -->
<div class="tab-pane" id="tab-confronto">
  <div style="display:grid;grid-template-columns:repeat(3,1fr);gap:14px;margin-bottom:18px" id="yoyCards"></div>
  <div class="chart-card" style="margin-bottom:16px">
    <h6 id="yoyChartTitle">Confronto anno su anno</h6>
    <canvas id="yoyChart" height="140"></canvas>
  </div>
  <div class="chart-card" style="padding:0;overflow:hidden">
    <div style="padding:14px 18px 6px"><h6 style="margin-bottom:0">Variazione uscite per categoria</h6></div>
    <table class="data-table">
      <thead><tr>
        <th>Categoria</th>
        <th style="text-align:right" id="yoyPrevHdr">Anno prec.</th>
        <th style="text-align:right" id="yoyCurHdr">Anno corr.</th>
        <th style="text-align:right">Variazione</th>
      </tr></thead>
      <tbody id="yoyBody"></tbody>
    </table>
  </div>
</div>

<!-- ── TAB: Top Spese ────────────────────────────────── -->
<div class="tab-pane" id="tab-topspese">
  <div class="filter-bar" style="margin-bottom:14px">
    <select class="form-select" id="topMonth">
      <option value="">Tutto l'anno</option>
      <option value="1">Gennaio</option><option value="2">Febbraio</option>
      <option value="3">Marzo</option><option value="4">Aprile</option>
      <option value="5">Maggio</option><option value="6">Giugno</option>
      <option value="7">Luglio</option><option value="8">Agosto</option>
      <option value="9">Settembre</option><option value="10">Ottobre</option>
      <option value="11">Novembre</option><option value="12">Dicembre</option>
    </select>
    <select class="form-select" id="topLimit">
      <option value="10">Top 10</option><option value="20">Top 20</option><option value="50">Top 50</option>
    </select>
    <button class="btn btn-ghost btn-sm" onclick="loadTop()">Aggiorna</button>
  </div>
  <div class="chart-card" style="padding:0;overflow:hidden">
    <table class="data-table">
      <thead><tr>
        <th>#</th><th>Data</th><th>Descrizione</th><th>Categoria</th><th style="text-align:right">Importo</th>
      </tr></thead>
      <tbody id="topBody"></tbody>
    </table>
    <div class="empty-state" id="topEmpty" style="display:none;padding:30px 16px">
      <div class="empty-icon" style="font-size:1.8rem">📭</div><p>Nessuna spesa trovata</p>
    </div>
  </div>
</div>
{% endblock %}

{% block scripts %}
<script>
let annualChart, annualCatChart, trendChart, yoyChart;
const MONTHS_IT=['Gennaio','Febbraio','Marzo','Aprile','Maggio','Giugno','Luglio','Agosto','Settembre','Ottobre','Novembre','Dicembre'];
const MONTHS_SH=['Gen','Feb','Mar','Apr','Mag','Giu','Lug','Ago','Set','Ott','Nov','Dic'];

// ── Tab switching ─────────────────────────────────────────────────────────────
function switchTab(name) {
  document.querySelectorAll('.tab-btn').forEach((b,i)=>{
    const tabs=['annuale','tendenze','confronto','topspese'];
    b.className='tab-btn'+(tabs[i]===name?' active':'');
  });
  document.querySelectorAll('.tab-pane').forEach(p=>{
    p.className='tab-pane'+(p.id==='tab-'+name?' active':'');
  });
  if(name==='tendenze' && !trendChart) loadTrends();
  if(name==='confronto') loadYoY();
  if(name==='topspese') loadTop();
}

// ── Year init ─────────────────────────────────────────────────────────────────
async function initYears(){
  const years=await fetch('/api/years').then(r=>r.json());
  const sel=document.getElementById('rYear');
  const cur=String(new Date().getFullYear());
  const set=new Set([...years,cur]);
  [...set].sort((a,b)=>b-a).forEach(y=>{
    const o=document.createElement('option');
    o.value=y;o.textContent=y;if(y===cur)o.selected=true;sel.appendChild(o);
  });
  loadAll();
}

function loadAll(){ loadAnnual(); if(document.getElementById('tab-tendenze').classList.contains('active')) loadTrends(); }

// ── Annual tab ────────────────────────────────────────────────────────────────
async function loadAnnual(){
  const year=document.getElementById('rYear').value;
  const d=await fetch(`/api/reports/monthly?year=${year}`).then(r=>r.json());

  let totIn=0,totOut=0;
  d.monthly.forEach(m=>{totIn+=m.entrate;totOut+=m.uscite;});
  const totBal=totIn-totOut;
  const active=d.monthly.filter(m=>m.entrate>0||m.uscite>0).length||1;

  document.getElementById('a-in').textContent=fmt(totIn);
  document.getElementById('a-out').textContent=fmt(totOut);
  const bEl=document.getElementById('a-bal');
  bEl.textContent=fmt(totBal);bEl.className='stat-value '+(totBal>=0?'amt-in':'amt-out');
  document.getElementById('a-avg').textContent=fmt(totBal/active);

  if(annualChart) annualChart.destroy();
  annualChart=new Chart(document.getElementById('annualChart'),{
    type:'bar',
    data:{labels:MONTHS_SH,datasets:[
      {label:'Entrate',data:d.monthly.map(m=>m.entrate),backgroundColor:'rgba(16,185,129,.75)',borderRadius:5},
      {label:'Uscite', data:d.monthly.map(m=>m.uscite), backgroundColor:'rgba(239,68,68,.75)', borderRadius:5},
      {label:'Saldo',  data:d.monthly.map(m=>m.saldo),  type:'line',borderColor:'#4f46e5',
       backgroundColor:'rgba(79,70,229,.08)',fill:true,tension:.3,pointRadius:3,pointBackgroundColor:'#4f46e5'}
    ]},
    options:{responsive:true,plugins:{legend:{position:'top'},tooltip:{callbacks:{label:ctx=>` ${fmt(ctx.raw)}`}}},
      scales:{y:{ticks:{callback:v=>'€'+v.toLocaleString('it-IT')},grid:{color:'#f1f5f9'}},x:{grid:{display:false}}}}
  });

  // Monthly table
  const tbody=document.getElementById('monthBody'),tfoot=document.getElementById('monthFoot');
  tbody.innerHTML='';
  d.monthly.forEach(m=>{
    const has=m.entrate>0||m.uscite>0;
    const tr=document.createElement('tr');
    if(!has) tr.style.opacity='.4';
    const sal=m.saldo;
    tr.innerHTML=`<td style="font-weight:${has?600:400}">${m.label}</td>
      <td style="text-align:right;color:var(--income)">${m.entrate>0?fmt(m.entrate):'—'}</td>
      <td style="text-align:right;color:var(--expense)">${m.uscite>0?fmt(m.uscite):'—'}</td>
      <td style="text-align:right;font-weight:700;color:${sal>=0?'var(--income)':'var(--expense)'}">${has?fmt(sal):'—'}</td>`;
    tbody.appendChild(tr);
  });
  tfoot.innerHTML=`<tr>
    <td style="padding:10px 13px">TOTALE</td>
    <td style="text-align:right;padding:10px 13px;color:var(--income)">${fmt(totIn)}</td>
    <td style="text-align:right;padding:10px 13px;color:var(--expense)">${fmt(totOut)}</td>
    <td style="text-align:right;padding:10px 13px;color:${totBal>=0?'var(--income)':'var(--expense)'}">${fmt(totBal)}</td>
  </tr>`;

  // Category donut
  if(annualCatChart) annualCatChart.destroy();
  const legend=document.getElementById('catLegend'); legend.innerHTML='';
  if(d.by_category.length){
    annualCatChart=new Chart(document.getElementById('annualCatChart'),{
      type:'doughnut',
      data:{labels:d.by_category.map(x=>x.icon+' '+x.name),datasets:[{
        data:d.by_category.map(x=>x.total),backgroundColor:d.by_category.map(x=>x.color),borderWidth:2,borderColor:'#fff'
      }]},
      options:{cutout:'58%',plugins:{legend:{display:false},tooltip:{callbacks:{label:ctx=>` ${fmt(ctx.raw)}`}}}}
    });
    d.by_category.slice(0,8).forEach(cat=>{
      const pct=totOut>0?((cat.total/totOut)*100).toFixed(1):0;
      const row=document.createElement('div');
      row.style.cssText='display:flex;align-items:center;gap:6px;font-size:.78rem';
      row.innerHTML=`<span style="width:9px;height:9px;border-radius:50%;background:${cat.color};flex-shrink:0"></span>
        <span style="flex:1">${cat.icon} ${cat.name}</span>
        <span style="color:var(--muted)">${pct}%</span>
        <span style="font-weight:700;min-width:65px;text-align:right">${fmt(cat.total)}</span>`;
      legend.appendChild(row);
    });
  }
}

// ── Trends tab ────────────────────────────────────────────────────────────────
async function loadTrends(){
  const d=await fetch('/api/reports/trends').then(r=>r.json());

  if(trendChart) trendChart.destroy();
  const colors=d.categories.map(c=>c.color);
  trendChart=new Chart(document.getElementById('trendLineChart'),{
    type:'line',
    data:{labels:d.month_labels,datasets:d.categories.map((cat,i)=>({
      label:cat.icon+' '+cat.name, data:cat.monthly_data,
      borderColor:cat.color, backgroundColor:cat.color+'18',
      tension:.3, pointRadius:2, borderWidth:2, fill:false
    }))},
    options:{responsive:true,
      plugins:{legend:{position:'right',labels:{font:{size:10},boxWidth:10,padding:6}}},
      scales:{y:{ticks:{callback:v=>'€'+v.toLocaleString('it-IT')},grid:{color:'#f1f5f9'}},x:{grid:{display:false},ticks:{font:{size:10}}}}}
  });

  const tbody=document.getElementById('trendsBody'); tbody.innerHTML='';
  d.categories.forEach(cat=>{
    // Trend direction: compare last 3m avg vs prev 3m avg
    const data=cat.monthly_data;
    const last3=data.slice(-3).reduce((a,b)=>a+b,0)/3;
    const prev3=data.slice(-6,-3).reduce((a,b)=>a+b,0)/3;
    let trend='→';
    if(last3>prev3*1.1) trend='<span style="color:var(--expense)">↑ +'+Math.round(((last3-prev3)/prev3)*100)+'%</span>';
    else if(last3<prev3*0.9) trend='<span style="color:var(--income)">↓ '+Math.round(((last3-prev3)/prev3)*100)+'%</span>';
    const tr=document.createElement('tr');
    tr.innerHTML=`
      <td><span class="cat-dot" style="background:${cat.color}"></span>${cat.icon} ${cat.name}</td>
      <td style="text-align:right;font-weight:700">${fmt(cat.average)}</td>
      <td style="text-align:right;color:var(--muted)">${fmt(cat.total)}</td>
      <td style="text-align:right">${trend}</td>`;
    tbody.appendChild(tr);
  });
}

// ── Year-over-year tab ────────────────────────────────────────────────────────
async function loadYoY(){
  const d=await fetch('/api/reports/trends').then(r=>r.json());
  const {yoy}=d;

  document.getElementById('yoyChartTitle').textContent=`${yoy.prev_year} vs ${yoy.cur_year}`;
  document.getElementById('yoyPrevHdr').textContent=yoy.prev_year;
  document.getElementById('yoyCurHdr').textContent=yoy.cur_year;

  const cards=document.getElementById('yoyCards'); cards.innerHTML='';
  const metrics=[
    {label:'Entrate',prev:yoy.prev_entrate,cur:yoy.cur_entrate,up:true},
    {label:'Uscite', prev:yoy.prev_uscite, cur:yoy.cur_uscite, up:false},
    {label:'Saldo',  prev:yoy.prev_entrate-yoy.prev_uscite, cur:yoy.cur_entrate-yoy.cur_uscite, up:true}
  ];
  metrics.forEach(m=>{
    const diff=m.cur-m.prev;
    const pct=m.prev>0?Math.abs(((diff)/m.prev)*100).toFixed(1):null;
    const isUp=diff>=0;
    const goodUp=m.up?isUp:!isUp;
    const card=document.createElement('div'); card.className='stat-card';
    card.innerHTML=`<div style="flex:1">
      <div class="stat-label">${m.label}</div>
      <div class="stat-value" style="font-size:1.2rem">${fmt(m.cur)}</div>
      <div style="font-size:.75rem;color:var(--muted);margin-top:3px">${yoy.prev_year}: ${fmt(m.prev)}</div>
      ${pct?`<div style="margin-top:4px"><span class="stat-chg ${goodUp?'up':'down'}">${isUp?'↑':'↓'} ${pct}%</span></div>`:''}
    </div>`;
    cards.appendChild(card);
  });

  if(yoyChart) yoyChart.destroy();
  yoyChart=new Chart(document.getElementById('yoyChart'),{
    type:'bar',
    data:{labels:MONTHS_SH,datasets:[
      {label:String(yoy.prev_year)+' uscite',data:yoy.yoy_cats.map(()=>0),backgroundColor:'rgba(99,102,241,.45)',borderRadius:5},
      {label:String(yoy.cur_year)+' uscite', data:yoy.yoy_cats.map(()=>0),backgroundColor:'rgba(239,68,68,.65)', borderRadius:5}
    ]},
    options:{responsive:true,plugins:{legend:{position:'top'}},
      scales:{y:{ticks:{callback:v=>'€'+v.toLocaleString('it-IT')},grid:{color:'#f1f5f9'}},x:{grid:{display:false}}}}
  });

  // YoY by-month chart: load actual monthly data for both years
  const [cy,py]=await Promise.all([
    fetch(`/api/reports/monthly?year=${yoy.cur_year}`).then(r=>r.json()),
    fetch(`/api/reports/monthly?year=${yoy.prev_year}`).then(r=>r.json())
  ]);
  yoyChart.data.datasets[0].data=py.monthly.map(m=>m.uscite);
  yoyChart.data.datasets[1].data=cy.monthly.map(m=>m.uscite);
  yoyChart.update();

  // Category table
  const tbody=document.getElementById('yoyBody'); tbody.innerHTML='';
  yoy.yoy_cats.sort((a,b)=>b.cur-a.cur).forEach(cat=>{
    const diff=cat.diff, pct=cat.pct;
    const isUp=diff>0;
    const tr=document.createElement('tr');
    tr.innerHTML=`
      <td><span class="cat-dot" style="background:${cat.color}"></span>${cat.icon} ${cat.name}</td>
      <td style="text-align:right;color:var(--muted)">${fmt(cat.prev)}</td>
      <td style="text-align:right;font-weight:700">${fmt(cat.cur)}</td>
      <td style="text-align:right">
        ${pct!==null?`<span class="stat-chg ${isUp?'down':'up'}">${isUp?'↑':'↓'} ${Math.abs(pct)}%</span>`:'—'}
      </td>`;
    tbody.appendChild(tr);
  });
}

// ── Top spese tab ─────────────────────────────────────────────────────────────
async function loadTop(){
  const year=document.getElementById('rYear').value;
  const month=document.getElementById('topMonth').value;
  const limit=document.getElementById('topLimit').value;
  let url=`/api/reports/trends`;  // placeholder, but we use transactions API
  const p=new URLSearchParams({year,limit});
  if(month) p.append('month',month);
  const rows=await fetch('/api/transactions?type=uscita&'+p).then(r=>r.json());
  const sorted=rows.sort((a,b)=>b.amount-a.amount).slice(0,parseInt(limit));

  const tbody=document.getElementById('topBody'), empty=document.getElementById('topEmpty');
  tbody.innerHTML='';
  if(!sorted.length){document.getElementById('topBody').closest('table').style.display='none';empty.style.display='block';return;}
  document.getElementById('topBody').closest('table').style.display='';empty.style.display='none';
  sorted.forEach((tx,i)=>{
    const tr=document.createElement('tr');
    const catH=tx.cat_name?`<span class="cat-dot" style="background:${tx.color}"></span>${tx.cat_name}`:'—';
    tr.innerHTML=`
      <td style="color:var(--muted);font-weight:700">#${i+1}</td>
      <td style="color:var(--muted);white-space:nowrap">${fmtDate(tx.date)}</td>
      <td style="font-weight:500">${tx.description}</td>
      <td style="font-size:.8rem">${catH}</td>
      <td style="text-align:right" class="amt-out">${fmt(tx.amount)}</td>`;
    tbody.appendChild(tr);
  });
}

initYears();
</script>
{% endblock %}
