<div class="card">
  <h1>Controle de Documentos Fiscais</h1>
  <p class="muted">Listagem e download de documentos por período, tipo e busca.</p>

  <!-- Filtros -->
  <div style="display:flex;gap:0.75rem;flex-wrap:wrap;align-items:flex-end;margin:0.5rem 0;">
    <div class="form-group">
      <label for="tipoSelect">Tipo</label>
      <select id="tipoSelect" class="input">
        <option value="">Todos</option>
        <option value="SPED">SPED</option>
        <option value="ANEXO">Anexo</option>
      </select>
    </div>
    <div class="form-group">
      <label for="startDate">Início</label>
      <input id="startDate" type="date" class="input" />
    </div>
    <div class="form-group">
      <label for="endDate">Fim</label>
      <input id="endDate" type="date" class="input" />
    </div>
    <div class="form-group" style="min-width:220px;flex:1;">
      <label for="q">Busca</label>
      <input id="q" type="text" class="input" placeholder="Chave, série/número ou nome" />
    </div>
    <button id="btnBuscar" class="btn">Buscar</button>
    <div style="display:flex;gap:0.25rem;align-items:center;">
      <label for="sepSelect" class="muted" style="font-size:0.9rem;">CSV:</label>
      <select id="sepSelect" class="input" style="width:110px;">
        <option value=";">Ponto e vírgula</option>
        <option value=",">Vírgula</option>
        <option value="\t">Tabulação</option>
      </select>
      <button id="btnExportCsv" class="btn btn-secondary" disabled>Exportar</button>
    </div>
  </div>

  <!-- Upload básico -->
  <div class="card" style="margin: 0.5rem 0;">
    <h3>Upload de Documento</h3>
    <div style="display:flex;gap:0.75rem;flex-wrap:wrap;align-items:flex-end;margin-top:0.5rem;">
      <div class="form-group">
        <label for="uploadTipo">Tipo de destino</label>
        <select id="uploadTipo" class="input">
          <option value="ANEXO">Anexo</option>
          <option value="SPED">SPED</option>
        </select>
      </div>
      <div class="form-group" style="min-width:260px;flex:1;">
        <label for="fileInput">Arquivo</label>
        <input id="fileInput" type="file" class="input" />
      </div>
      <button id="btnUpload" class="btn">Enviar</button>
      <div id="uploadStatus" class="muted"></div>
    </div>
  </div>

  <div id="docsSummary" class="muted" style="margin:0.25rem 0;">Sem filtros aplicados.</div>

  <!-- Tabela -->
  <div class="table-responsive">
    <table class="table">
      <thead>
        <tr>
          <th>#</th>
          <th>Tipo</th>
          <th>Nome</th>
          <th>Data</th>
          <th>Tamanho</th>
          <th>Caminho</th>
          <th>Ações</th>
        </tr>
      </thead>
      <tbody id="docsRows"><tr><td colspan="7" class="muted">Carregando…</td></tr></tbody>
    </table>
  </div>

  <div id="docsPagination" class="muted" style="margin-top:0.5rem;"></div>

  <script>
    (function(){
      const tipoSelect = document.getElementById('tipoSelect');
      const startDate = document.getElementById('startDate');
      const endDate = document.getElementById('endDate');
      const q = document.getElementById('q');
      const btnBuscar = document.getElementById('btnBuscar');
      const btnExportCsv = document.getElementById('btnExportCsv');
      const sepSelect = document.getElementById('sepSelect');
      const summary = document.getElementById('docsSummary');
      const rowsEl = document.getElementById('docsRows');
      const pagEl = document.getElementById('docsPagination');
      const uploadTipo = document.getElementById('uploadTipo');
      const fileInput = document.getElementById('fileInput');
      const btnUpload = document.getElementById('btnUpload');
      const uploadStatus = document.getElementById('uploadStatus');

      let lastData = [];
      let lastPagination = { total: 0, page: 1, per_page: 20, pages: 0 };

      function fmtDate(iso){
        try { const d = new Date(iso); return d.toLocaleString('pt-BR'); } catch(e){ return iso; }
      }
      function fmtSize(bytes){
        const b = Number(bytes||0); if (b < 1024) return b + ' B';
        const kb = b/1024; if (kb < 1024) return kb.toFixed(1) + ' KB';
        const mb = kb/1024; return mb.toFixed(1) + ' MB';
      }
      function escapeHtml(s){ return String(s||'').replace(/[&<>"]/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c])); }

      function buildQuery(page){
        const params = new URLSearchParams();
        const tipo = (tipoSelect.value||'').trim(); if (tipo) params.set('tipo', tipo);
        const s = (startDate.value||'').trim(); if (s) params.set('start', s);
        const e = (endDate.value||'').trim(); if (e) params.set('end', e);
        const qq = (q.value||'').trim(); if (qq) params.set('q', qq);
        if (page) params.set('page', page);
        params.set('per_page', '20');
        return params.toString();
      }

      async function buscar(page){
        rowsEl.innerHTML = '<tr><td colspan="7" class="muted">Carregando…</td></tr>';
        btnExportCsv.disabled = true;
        const query = buildQuery(page || 1);
        const resp = await apiRequest('/api/fiscal/documentos?' + query, { headers: { 'Accept': 'application/json' } });
        const json = await resp.json().catch(()=>({}));
        const data = json.data || json.items || [];
        lastData = data;
        lastPagination = json.pagination || { total: (data||[]).length, page: 1, per_page: 20, pages: 1 };
        render(data, lastPagination);
      }

      function render(items, pg){
        // Resumo
        const t = (tipoSelect.value||'') || 'Todos';
        const s = (startDate.value||''); const e = (endDate.value||'');
        const qq = (q.value||'');
        summary.textContent = `Tipo: ${t}${s||e ? ` • Período: ${s||'?'} a ${e||'?'} ` : ''}${qq ? ` • Busca: ${qq}` : ''}`;

        // Tabela
        if (!Array.isArray(items) || items.length === 0){
          rowsEl.innerHTML = '<tr><td colspan="7" class="muted">Sem dados</td></tr>';
          btnExportCsv.disabled = true;
        } else {
          const html = items.map((it, idx)=>{
            const id = encodeURIComponent(it.id || btoa(it.caminho||String(idx)));
            const dt = fmtDate(it.data);
            const sz = fmtSize(it.tamanho);
            const tipo = escapeHtml(it.tipo||'-');
            const nome = escapeHtml(it.nome||'-');
            const cam = escapeHtml(it.caminho||'-');
            const url = it.url || ('/api/fiscal/documentos/download?id=' + id);
            return `<tr>
              <td>${(pg.page-1)*pg.per_page + idx + 1}</td>
              <td>${tipo}</td>
              <td>${nome}</td>
              <td>${dt}</td>
              <td>${sz}</td>
              <td style="max-width:380px; overflow:hidden; text-overflow:ellipsis;">${cam}</td>
              <td><a class="btn btn-secondary" href="${url}">Download</a></td>
            </tr>`;
          }).join('');
          rowsEl.innerHTML = html;
          btnExportCsv.disabled = false;
        }

        // Paginação
        const pages = Math.max(1, parseInt(pg.pages||1,10));
        const page = Math.max(1, parseInt(pg.page||1,10));
        pagEl.innerHTML = `Página ${page} de ${pages} • Total ${pg.total||items.length}`;
      }

      function exportCsv(){
        const sep = sepSelect.value || ';';
        const bom = new Uint8Array([0xEF,0xBB,0xBF]);
        const headers = ['#','Tipo','Nome','Data','Tamanho','Caminho'];
        let csv = headers.join(sep) + '\n';
        lastData.forEach((it, idx)=>{
          const dt = fmtDate(it.data);
          const sz = fmtSize(it.tamanho);
          const row = [String(idx+1), it.tipo||'', (it.nome||'').replace(/\n/g,' '), dt, sz, (it.caminho||'').replace(/\n/g,' ')];
          csv += row.map(v => String(v).includes(sep) ? '"' + String(v).replace(/"/g,'""') + '"' : String(v)).join(sep) + '\n';
        });
        const blob = new Blob([bom, csv], { type: 'text/csv;charset=utf-8;' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a'); a.href = url; a.download = 'documentos_fiscais.csv'; a.click();
        setTimeout(()=>URL.revokeObjectURL(url), 2000);
      }

      btnBuscar.addEventListener('click', ()=>buscar(1));
      btnExportCsv.addEventListener('click', exportCsv);
      setTimeout(()=>buscar(1), 50);

      async function uploadDoc(){
        uploadStatus.textContent = '';
        const f = fileInput.files && fileInput.files[0];
        if (!f) { alert('Selecione um arquivo para enviar.'); return; }
        const tipo = (uploadTipo.value||'ANEXO');
        const fd = new FormData();
        fd.append('file', f);
        fd.append('tipo', tipo);
        btnUpload.disabled = true; btnUpload.textContent = 'Enviando…';
        try {
          const resp = await apiRequest('/api/fiscal/documentos/upload', { method: 'POST', body: fd });
          const json = await resp.json().catch(()=>({}));
          if (!json.ok) { throw new Error(json.error || 'Falha no upload'); }
          uploadStatus.textContent = 'Upload concluído: ' + (json.item && json.item.nome ? json.item.nome : '');
          fileInput.value = '';
          buscar(1);
        } catch (err){
          alert('Erro: ' + (err && err.message ? err.message : String(err)));
        } finally {
          btnUpload.disabled = false; btnUpload.textContent = 'Enviar';
        }
      }
      btnUpload.addEventListener('click', uploadDoc);
    })();
  </script>
</div>