{% extends 'base.html' %}
{% set active = 'transactions' %}
{% block page_title %}Transazioni{% endblock %}
{% block header_title %}Transazioni{% endblock %}

{% block topbar_extra %}
<div style="display:flex;gap:6px">
  <div style="position:relative">
    <button class="btn btn-outline btn-sm" onclick="toggleExportMenu()">📤 Esporta ▾</button>
    <div id="exportMenu" style="display:none;position:absolute;right:0;top:38px;background:#fff;border:1px solid var(--border);border-radius:10px;box-shadow:0 4px 16px rgba(0,0,0,.12);min-width:160px;z-index:100">
      <div onclick="exportData('csv')"   style="padding:9px 16px;cursor:pointer;font-size:.875rem;display:flex;align-items:center;gap:8px">📄 CSV (mese)</div>
      <div onclick="exportData('excel')" style="padding:9px 16px;cursor:pointer;font-size:.875rem;display:flex;align-items:center;gap:8px">📊 Excel (mese)</div>
      <div onclick="exportData('csv',true)"   style="padding:9px 16px;cursor:pointer;font-size:.875rem;display:flex;align-items:center;gap:8px;border-top:1px solid var(--border)">📄 CSV (tutto)</div>
      <div onclick="exportData('excel',true)" style="padding:9px 16px;cursor:pointer;font-size:.875rem;display:flex;align-items:center;gap:8px">📊 Excel (tutto)</div>
    </div>
  </div>
  <button class="btn btn-outline btn-sm" onclick="document.getElementById('importModal').classList.add('open')">📥 Importa</button>
</div>
{% endblock %}

{% block content %}
<!-- Filter bar -->
<div class="filter-bar" style="margin-bottom:14px">
  <select class="form-select" id="fYear"  onchange="loadTx()"></select>
  <select class="form-select" id="fMonth" onchange="loadTx()">
    <option value="">Tutti i mesi</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="fType" onchange="loadTx()">
    <option value="">Tutte</option>
    <option value="entrata">↑ Entrate</option>
    <option value="uscita">↓ Uscite</option>
  </select>
  <select class="form-select" id="fCat" onchange="loadTx()"><option value="">Tutte le categorie</option></select>
  <select class="form-select" id="fTag" onchange="loadTx()"><option value="">Tutti i tag</option></select>
  <input type="text"   class="form-control" id="fSearch" placeholder="Descrizione…" oninput="debounceLoad()" style="min-width:150px">
  <input type="number" class="form-control" id="fAmtMin" placeholder="€ min"  oninput="debounceLoad()" style="width:80px">
  <input type="number" class="form-control" id="fAmtMax" placeholder="€ max"  oninput="debounceLoad()" style="width:80px">
  <button class="btn btn-ghost btn-sm" onclick="resetFilters()">↺ Reset</button>
  <span id="txCount" style="margin-left:auto;font-size:.8rem;color:var(--muted)"></span>
</div>

<!-- Summary -->
<div style="display:grid;grid-template-columns:repeat(3,1fr);gap:10px;margin-bottom:14px">
  <div class="stat-card" style="padding:12px 16px">
    <div class="stat-icon" style="background:#d1fae5;width:36px;height:36px;font-size:1rem">↑</div>
    <div><div class="stat-label">Entrate filtrate</div><div class="stat-value amt-in" style="font-size:1.15rem" id="sumIn">—</div></div>
  </div>
  <div class="stat-card" style="padding:12px 16px">
    <div class="stat-icon" style="background:#fee2e2;width:36px;height:36px;font-size:1rem">↓</div>
    <div><div class="stat-label">Uscite filtrate</div><div class="stat-value amt-out" style="font-size:1.15rem" id="sumOut">—</div></div>
  </div>
  <div class="stat-card" style="padding:12px 16px">
    <div class="stat-icon" style="background:#e0e7ff;width:36px;height:36px;font-size:1rem">⚖</div>
    <div><div class="stat-label">Saldo</div><div class="stat-value" style="font-size:1.15rem" id="sumBal">—</div></div>
  </div>
</div>

<!-- Table -->
<div class="chart-card" style="padding:0;overflow:hidden">
  <table class="data-table" id="txTable">
    <thead><tr>
      <th style="cursor:pointer" onclick="sortBy('date')">Data <span id="sort-date"></span></th>
      <th>Descrizione</th>
      <th>Categoria</th>
      <th>Tag</th>
      <th style="cursor:pointer" onclick="sortBy('type')">Tipo <span id="sort-type"></span></th>
      <th style="text-align:right;cursor:pointer" onclick="sortBy('amount')">Importo <span id="sort-amount"></span></th>
      <th style="text-align:center;width:80px">Azioni</th>
    </tr></thead>
    <tbody id="txBody"></tbody>
  </table>
  <div class="empty-state" id="txEmpty" style="display:none">
    <div class="empty-icon">📭</div>
    <p>Nessuna transazione trovata</p>
    <button class="btn btn-primary btn-sm" style="margin-top:12px" onclick="openTransactionModal()">Aggiungi</button>
  </div>
</div>

<!-- Import Modal -->
<div class="modal-overlay" id="importModal" onclick="if(event.target===this)this.classList.remove('open')">
  <div class="modal-box" style="max-width:460px">
    <button class="modal-close" onclick="document.getElementById('importModal').classList.remove('open')">×</button>
    <h5>📥 Importa CSV</h5>
    <p style="font-size:.82rem;color:var(--muted);margin-bottom:14px">
      Formato supportato: <code>Data, Descrizione, Importo, Tipo, Categoria, Note</code><br>
      Data: <code>DD/MM/YYYY</code> o <code>YYYY-MM-DD</code> · Tipo: <code>entrata</code> / <code>uscita</code>
    </p>
    <div class="form-group">
      <label class="form-label">Seleziona file CSV</label>
      <input type="file" class="form-control" id="importFile" accept=".csv" style="padding:5px">
    </div>
    <div id="importResult" style="display:none;margin:10px 0;font-size:.82rem"></div>
    <div style="display:flex;gap:8px;justify-content:flex-end">
      <button class="btn btn-ghost" onclick="document.getElementById('importModal').classList.remove('open')">Annulla</button>
      <button class="btn btn-primary" onclick="importCSV()">Importa</button>
    </div>
  </div>
</div>
{% endblock %}

{% block scripts %}
<script>
let allTx = [], sortCol = 'date', sortDir = -1, debTimer;

async function initFilters() {
  const years = await fetch('/api/years').then(r=>r.json());
  const fYear = document.getElementById('fYear');
  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;
    fYear.appendChild(o);
  });
  document.getElementById('fMonth').value = new Date().getMonth()+1;

  const fCat = document.getElementById('fCat');
  categories.forEach(c => {
    const o=document.createElement('option'); o.value=c.id; o.textContent=c.icon+' '+c.name; fCat.appendChild(o);
  });

  const fTag = document.getElementById('fTag');
  allTags.forEach(t => {
    const o=document.createElement('option'); o.value=t.name; o.textContent=t.name; fTag.appendChild(o);
  });

  loadTx();
}

async function loadTx() {
  const p = new URLSearchParams();
  const y=document.getElementById('fYear').value, m=document.getElementById('fMonth').value;
  const type=document.getElementById('fType').value, cat=document.getElementById('fCat').value;
  const tag=document.getElementById('fTag').value, search=document.getElementById('fSearch').value.trim();
  const amin=document.getElementById('fAmtMin').value, amax=document.getElementById('fAmtMax').value;
  if(y) p.append('year',y); if(m) p.append('month',m);
  if(type) p.append('type',type); if(cat) p.append('category_id',cat);
  if(tag) p.append('tag',tag); if(search) p.append('search',search);
  if(amin) p.append('amount_min',amin); if(amax) p.append('amount_max',amax);
  allTx = await fetch('/api/transactions?'+p).then(r=>r.json());
  renderTable();
}

function debounceLoad() { clearTimeout(debTimer); debTimer = setTimeout(loadTx,300); }

function resetFilters() {
  document.getElementById('fMonth').value=new Date().getMonth()+1;
  ['fType','fCat','fTag'].forEach(id=>document.getElementById(id).value='');
  ['fSearch','fAmtMin','fAmtMax'].forEach(id=>document.getElementById(id).value='');
  loadTx();
}

function sortBy(col) {
  sortDir = sortCol===col ? sortDir*-1 : -1; sortCol=col; renderTable();
}

function renderTable() {
  const sorted = [...allTx].sort((a,b) => {
    let va=a[sortCol], vb=b[sortCol];
    if(sortCol==='amount'){va=+va;vb=+vb;}
    return va<vb?-sortDir:va>vb?sortDir:0;
  });
  ['date','type','amount'].forEach(c => {
    document.getElementById('sort-'+c).textContent = sortCol===c?(sortDir===1?'↑':'↓'):'';
  });

  let sumIn=0,sumOut=0;
  allTx.forEach(t => t.type==='entrata'?sumIn+=t.amount:sumOut+=t.amount);
  const bal=sumIn-sumOut;
  document.getElementById('sumIn').textContent  = fmt(sumIn);
  document.getElementById('sumOut').textContent = fmt(sumOut);
  const bEl=document.getElementById('sumBal');
  bEl.textContent=fmt(bal); bEl.className='stat-value '+(bal>=0?'amt-in':'amt-out')+' font-size:1.15rem';
  document.getElementById('txCount').textContent = `${allTx.length} voci`;

  const tbody=document.getElementById('txBody'), empty=document.getElementById('txEmpty');
  tbody.innerHTML='';
  if (!sorted.length) {
    document.getElementById('txTable').style.display='none'; empty.style.display='block'; return;
  }
  document.getElementById('txTable').style.display=''; empty.style.display='none';

  sorted.forEach(tx => {
    const tr=document.createElement('tr');
    const catH = tx.cat_name ? `<span class="cat-dot" style="background:${tx.color}"></span>${tx.cat_name}` : '<span style="color:var(--muted)">—</span>';
    const tagH = (tx.tags||[]).map(t=>`<span class="tag-chip" style="background:${t.color}22;color:${t.color};border:1px solid ${t.color}44">${t.name}</span>`).join(' ');
    const recH = tx.receipt_path ? `<a href="${tx.receipt_path}" target="_blank" title="Vedi allegato" style="text-decoration:none">📎</a>` : '';
    tr.innerHTML=`
      <td style="color:var(--muted);white-space:nowrap">${fmtDate(tx.date)}</td>
      <td>
        <div style="font-weight:500;display:flex;align-items:center;gap:5px">${tx.description} ${recH}</div>
        ${tx.notes?`<div style="font-size:.72rem;color:var(--muted)">${tx.notes}</div>`:''}
      </td>
      <td style="font-size:.8rem">${catH}</td>
      <td style="font-size:.8rem">${tagH||'<span style="color:var(--muted)">—</span>'}</td>
      <td><span class="badge-${tx.type}">${tx.type==='entrata'?'↑ Entrata':'↓ Uscita'}</span></td>
      <td style="text-align:right;font-weight:700" class="${tx.type==='entrata'?'amt-in':'amt-out'}">${tx.type==='entrata'?'+':'−'}${fmt(tx.amount)}</td>
      <td style="text-align:center;white-space:nowrap">
        <button class="btn-icon" onclick="editTx(${tx.id})" title="Modifica">✏️</button>
        <button class="btn-icon" onclick="deleteTx(${tx.id})" title="Elimina">🗑️</button>
      </td>`;
    tbody.appendChild(tr);
  });
}

function editTx(id) {
  const tx=allTx.find(t=>t.id===id); if(tx) openTransactionModal(tx);
}
function deleteTx(id) {
  openConfirm(async()=>{
    await fetch(`/api/transactions/${id}`,{method:'DELETE'});
    showToast('Transazione eliminata'); loadTx();
  });
}
function onTxSaved() { loadTx(); }

// Export
function toggleExportMenu() {
  const m=document.getElementById('exportMenu');
  m.style.display=m.style.display==='none'?'block':'none';
}
document.addEventListener('click',e=>{
  if(!e.target.closest('[onclick="toggleExportMenu()"]') && !e.target.closest('#exportMenu'))
    document.getElementById('exportMenu').style.display='none';
});
function exportData(fmt,all=false) {
  const y=all?'':document.getElementById('fYear').value;
  const m=all?'':document.getElementById('fMonth').value;
  let url=`/api/export/${fmt}`;
  const p=new URLSearchParams();
  if(y) p.append('year',y); if(m) p.append('month',m);
  const qs=p.toString(); if(qs) url+='?'+qs;
  window.location=url;
  document.getElementById('exportMenu').style.display='none';
}

// Import
async function importCSV() {
  const file=document.getElementById('importFile').files[0];
  if(!file){showToast('Seleziona un file','error');return;}
  const fd=new FormData(); fd.append('file',file);
  const r=await fetch('/api/import/csv',{method:'POST',body:fd});
  const j=await r.json();
  const res=document.getElementById('importResult');
  res.style.display='block';
  if(j.success){
    res.innerHTML=`<div style="color:var(--income);font-weight:600">✅ ${j.imported} transazion${j.imported!==1?'i':'e'} importata${j.imported!==1?'e':''}</div>`
      +(j.errors.length?`<div style="color:var(--expense);margin-top:4px">${j.errors.slice(0,5).join('<br>')}</div>`:'');
    showToast(`${j.imported} righe importate`,'success');
    loadTx();
  } else {
    res.innerHTML=`<div style="color:var(--expense)">${j.error||'Errore'}</div>`;
  }
}

async function waitAndInit() {
  if(!categories.length) await loadCategories();
  if(!allTags.length) await loadTags();
  initFilters();
}
waitAndInit();
</script>
{% endblock %}
