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

{% block topbar_extra %}
<button class="btn btn-ghost" onclick="openRecModal()">+ Nuova ricorrente</button>
<button class="btn btn-primary" id="generateBtn" onclick="generateAll()" style="display:none">🔁 Genera pending</button>
{% endblock %}

{% block content %}
<div id="pendingNotif" style="display:none" class="notif-banner" style="margin-bottom:16px">
  <span>⏰</span><span id="pendingMsg"></span>
</div>

<div id="recList" style="display:flex;flex-direction:column;gap:10px"></div>
<div class="empty-state" id="recEmpty" style="display:none">
  <div class="empty-icon">🔁</div>
  <p>Nessuna transazione ricorrente configurata</p>
  <button class="btn btn-primary btn-sm" style="margin-top:12px" onclick="openRecModal()">Aggiungi la prima</button>
</div>

<!-- Recurring Modal -->
<div class="modal-overlay" id="recModal" onclick="if(event.target===this)closeRecModal()">
  <div class="modal-box">
    <button class="modal-close" onclick="closeRecModal()">×</button>
    <h5 id="recModalTitle">Nuova Transazione Ricorrente</h5>

    <div class="type-toggle">
      <button class="type-btn active-in" id="recBtnIn"  onclick="setRecType('entrata')">↑ Entrata</button>
      <button class="type-btn"           id="recBtnOut" onclick="setRecType('uscita')">↓ Uscita</button>
    </div>

    <div class="form-row form-row-2">
      <div class="form-group">
        <label class="form-label">Descrizione *</label>
        <input type="text" class="form-control" id="recDesc" placeholder="Es. Mutuo, Netflix…">
      </div>
      <div class="form-group">
        <label class="form-label">Importo (€) *</label>
        <input type="number" class="form-control" id="recAmount" min="0.01" step="0.01">
      </div>
    </div>

    <div class="form-row form-row-2">
      <div class="form-group">
        <label class="form-label">Categoria</label>
        <select class="form-select" id="recCategory"><option value="">— Nessuna —</option></select>
      </div>
      <div class="form-group">
        <label class="form-label">Frequenza *</label>
        <select class="form-select" id="recFreq" onchange="toggleDayField()">
          <option value="weekly">Settimanale</option>
          <option value="biweekly">Bisettimanale</option>
          <option value="monthly" selected>Mensile</option>
          <option value="yearly">Annuale</option>
        </select>
      </div>
    </div>

    <div class="form-row form-row-2">
      <div class="form-group" id="dayFieldWrap">
        <label class="form-label">Giorno del mese</label>
        <input type="number" class="form-control" id="recDay" min="1" max="31" value="1">
      </div>
      <div class="form-group">
        <label class="form-label">Prossima data</label>
        <input type="date" class="form-control" id="recNextDate">
      </div>
    </div>

    <div class="form-group">
      <label class="form-label">Note</label>
      <input type="text" class="form-control" id="recNotes" placeholder="Opzionale…">
    </div>

    <div class="form-group" id="recActiveWrap" style="display:none">
      <label style="display:flex;align-items:center;gap:8px;cursor:pointer;font-size:.875rem">
        <input type="checkbox" id="recActive" checked> Attiva
      </label>
    </div>

    <div style="display:flex;gap:8px;justify-content:flex-end;margin-top:6px">
      <button class="btn btn-ghost" onclick="closeRecModal()">Annulla</button>
      <button class="btn btn-primary" onclick="saveRec()">Salva</button>
    </div>
  </div>
</div>
{% endblock %}

{% block scripts %}
<script>
let recItems = [], recEditId = null, recType = 'entrata';
const FREQ_LABELS = {weekly:'Settimanale', biweekly:'Bisettimanale', monthly:'Mensile', yearly:'Annuale'};
const today = new Date().toISOString().split('T')[0];

async function loadRec() {
  recItems = await fetch('/api/recurring').then(r=>r.json());
  renderRec();
}

function renderRec() {
  const list  = document.getElementById('recList');
  const empty = document.getElementById('recEmpty');
  const genBtn= document.getElementById('generateBtn');
  const notif = document.getElementById('pendingNotif');
  list.innerHTML = '';

  const pending = recItems.filter(r => r.active && r.next_date <= today);
  if (pending.length) {
    genBtn.style.display = '';
    document.getElementById('pendingMsg').textContent =
      `${pending.length} transazion${pending.length>1?'i':'e'} in sospeso da generare`;
    notif.style.display = 'flex';
  } else {
    genBtn.style.display = 'none'; notif.style.display = 'none';
  }

  if (!recItems.length) { empty.style.display='block'; return; }
  empty.style.display = 'none';

  // Sort: pending first, then by next_date
  const sorted = [...recItems].sort((a,b) => {
    const aP = a.next_date <= today ? 0 : 1;
    const bP = b.next_date <= today ? 0 : 1;
    if (aP !== bP) return aP - bP;
    return a.next_date.localeCompare(b.next_date);
  });

  sorted.forEach(rec => {
    const isPending = rec.active && rec.next_date <= today;
    const isInactive = !rec.active;
    const card = document.createElement('div');
    card.className = 'rec-card';
    if (isPending)  card.style.borderColor = '#fbbf24';
    if (isInactive) card.style.opacity = '.6';

    const daysUntil = Math.round((new Date(rec.next_date) - new Date()) / 86400000);
    let dueBadge = '';
    if (!rec.active)     dueBadge = `<span class="badge-pill" style="background:#f1f5f9;color:var(--muted)">In pausa</span>`;
    else if (isPending)  dueBadge = `<span class="badge-pill tl-warn-bg">⏰ In sospeso</span>`;
    else if (daysUntil<=3) dueBadge = `<span class="badge-pill tl-warn-bg">tra ${daysUntil}gg</span>`;
    else                   dueBadge = `<span class="badge-pill" style="background:#f1f5f9;color:var(--muted)">tra ${daysUntil}gg</span>`;

    card.innerHTML = `
      <div class="rec-icon" style="background:${rec.color||'#6366f1'}22">${rec.icon||'🔁'}</div>
      <div style="flex:1;min-width:0">
        <div style="font-weight:700;font-size:.95rem">${rec.description}</div>
        <div style="font-size:.78rem;color:var(--muted);margin-top:2px">
          ${FREQ_LABELS[rec.frequency]||rec.frequency} · ${rec.cat_name||'Nessuna categoria'}
        </div>
        <div style="margin-top:5px;display:flex;gap:6px;flex-wrap:wrap;align-items:center">
          ${dueBadge}
          <span style="font-size:.78rem;color:var(--muted)">prossima: ${fmtDate(rec.next_date)}</span>
        </div>
      </div>
      <div style="text-align:right;flex-shrink:0">
        <div class="${rec.type==='entrata'?'amt-in':'amt-out'}" style="font-size:1.05rem;font-weight:800">${rec.type==='entrata'?'+':'−'}${fmt(rec.amount)}</div>
        <div style="display:flex;gap:4px;justify-content:flex-end;margin-top:6px">
          <button class="btn-icon" onclick="editRec(${rec.id})" title="Modifica">✏️</button>
          <button class="btn-icon" onclick="deleteRec(${rec.id})" title="Elimina">🗑️</button>
        </div>
      </div>`;
    list.appendChild(card);
  });
}

async function generateAll() {
  const r = await fetch('/api/recurring/generate',{method:'POST'});
  const j = await r.json();
  showToast(`${j.count} transazion${j.count!==1?'i':'e'} generate`,'success');
  loadRec();
}

// ── Modal ─────────────────────────────────────────────────────────────────────
function openRecModal(rec=null) {
  recEditId = rec ? rec.id : null;
  recType   = rec ? rec.type : 'entrata';
  document.getElementById('recModalTitle').textContent = rec ? 'Modifica Ricorrente' : 'Nuova Transazione Ricorrente';
  document.getElementById('recDesc').value     = rec ? rec.description : '';
  document.getElementById('recAmount').value   = rec ? rec.amount : '';
  document.getElementById('recFreq').value     = rec ? rec.frequency : 'monthly';
  document.getElementById('recDay').value      = rec ? (rec.day_of_month||1) : 1;
  document.getElementById('recNextDate').value = rec ? rec.next_date : today;
  document.getElementById('recNotes').value    = rec ? (rec.notes||'') : '';
  document.getElementById('recActiveWrap').style.display = rec ? 'block' : 'none';
  if (rec) document.getElementById('recActive').checked = !!rec.active;
  setRecType(recType);
  populateRecCat(recType, rec ? rec.category_id : null);
  toggleDayField();
  document.getElementById('recModal').classList.add('open');
}
function closeRecModal() { document.getElementById('recModal').classList.remove('open'); }

function setRecType(type) {
  recType = type;
  document.getElementById('recBtnIn').className  = 'type-btn'+(type==='entrata'?' active-in':'');
  document.getElementById('recBtnOut').className = 'type-btn'+(type==='uscita'?' active-out':'');
  populateRecCat(type, null);
}
function populateRecCat(type, selId) {
  const sel = document.getElementById('recCategory');
  sel.innerHTML = '<option value="">— Nessuna —</option>';
  categories.filter(c=>c.type===type||c.type==='entrambi').forEach(c=>{
    const o=document.createElement('option'); o.value=c.id; o.textContent=c.icon+' '+c.name;
    if(selId&&c.id==selId) o.selected=true; sel.appendChild(o);
  });
}
function toggleDayField() {
  document.getElementById('dayFieldWrap').style.display =
    document.getElementById('recFreq').value==='monthly'?'block':'none';
}

async function saveRec() {
  const desc  = document.getElementById('recDesc').value.trim();
  const amt   = parseFloat(document.getElementById('recAmount').value);
  const freq  = document.getElementById('recFreq').value;
  const ndate = document.getElementById('recNextDate').value;
  if(!desc) { showToast('Inserisci la descrizione','error'); return; }
  if(!amt||amt<=0) { showToast('Importo non valido','error'); return; }
  if(!ndate) { showToast('Inserisci la prossima data','error'); return; }

  const catId = document.getElementById('recCategory').value;
  const payload = {
    description: desc, amount: amt, type: recType,
    category_id: catId ? parseInt(catId) : null,
    frequency: freq, day_of_month: parseInt(document.getElementById('recDay').value)||1,
    next_date: ndate, notes: document.getElementById('recNotes').value.trim(),
    active: recEditId ? (document.getElementById('recActive').checked?1:0) : 1
  };
  if (!recEditId) payload.start_date = ndate;

  const url    = recEditId ? `/api/recurring/${recEditId}` : '/api/recurring';
  const method = recEditId ? 'PUT' : 'POST';
  await fetch(url,{method,headers:{'Content-Type':'application/json'},body:JSON.stringify(payload)});
  showToast(recEditId?'Aggiornata':'Creata','success');
  closeRecModal(); loadRec();
}

function editRec(id) { const r=recItems.find(x=>x.id===id); if(r) openRecModal(r); }
function deleteRec(id) {
  openConfirm(async()=>{
    await fetch(`/api/recurring/${id}`,{method:'DELETE'});
    showToast('Eliminata'); loadRec();
  });
}

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