'use client';

import { Suspense, useEffect, useRef, useState } from 'react';
import { useSearchParams } from 'next/navigation';
import api from '@/lib/api';
import { KlavoNFSe } from '@/components/KlavoNFSe';
import { buildNfsePrint, NfsePrintItem } from '@/lib/nfse-print';

// Impressão em lote: /notas-fiscais/lote?ids=<id>,<id>,...
// Renderiza um DANFSe por página A4; "Imprimir / Salvar PDF" gera um único PDF.
// Com &autoprint=1 abre a janela de impressão assim que tudo carrega.
function LotePrint() {
  const searchParams = useSearchParams();
  const ids = (searchParams?.get('ids') ?? '').split(',').map((s) => s.trim()).filter(Boolean);
  const idsKey = ids.join(',');
  const autoPrint = searchParams?.get('autoprint') === '1';
  const printed = useRef(false);

  const [items, setItems]   = useState<NfsePrintItem[] | null>(null);
  const [failed, setFailed] = useState<string[]>([]);
  const [loaded, setLoaded] = useState(0);
  const [error, setError]   = useState<string | null>(null);

  useEffect(() => {
    if (!ids.length) { setError('Nenhuma nota informada (parâmetro ids).'); return; }

    (async () => {
      try {
        const tenant = (await api.get('/tenant')).data;
        const results: (NfsePrintItem | null)[] = new Array(ids.length).fill(null);
        const errs: string[] = [];

        // Carrega em grupos para não disparar dezenas de requisições de uma vez
        const CHUNK = 5;
        for (let i = 0; i < ids.length; i += CHUNK) {
          await Promise.all(ids.slice(i, i + CHUNK).map(async (id, j) => {
            try {
              const inv = (await api.get(`/invoices/${id}`)).data;
              results[i + j] = await buildNfsePrint(inv, tenant);
            } catch {
              errs.push(id);
            } finally {
              setLoaded((n) => n + 1);
            }
          }));
        }

        setFailed(errs);
        setItems(results.filter((r): r is NfsePrintItem => !!r));
      } catch (e: any) {
        setError(e?.response?.data?.message ?? e?.message ?? 'Erro ao carregar notas');
      }
    })();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [idsKey]);

  useEffect(() => {
    if (!autoPrint || !items?.length || printed.current) return;
    printed.current = true;
    const t = setTimeout(() => window.print(), 800);
    return () => clearTimeout(t);
  }, [autoPrint, items]);

  if (error) {
    return (
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', minHeight: '100vh', fontFamily: 'sans-serif', color: '#374151' }}>
        <div style={{ textAlign: 'center' }}>
          <p style={{ fontWeight: 600, marginBottom: 8 }}>Erro ao carregar NFS-e</p>
          <p style={{ fontSize: 14, color: '#6B7280' }}>{error}</p>
        </div>
      </div>
    );
  }

  if (!items) {
    return (
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', minHeight: '100vh', fontFamily: 'sans-serif', color: '#9CA3AF', fontSize: 14 }}>
        Carregando {loaded}/{ids.length} notas...
      </div>
    );
  }

  return (
    <div className="nfse-lote" style={{ background: '#E9E6DC', padding: '0 0 96px', minHeight: '100vh' }}>
      <div style={{ position: 'sticky', top: 0, zIndex: 10, paddingTop: 24, background: '#E9E6DC' }}>
      <div className="klavo-nfse-ctrl" style={{ marginBottom: 0 }}>
        <div className="title">
          DANFSe · {items.length} nota{items.length !== 1 ? 's' : ''}
          {failed.length > 0 && <span style={{ color: '#B91C1C' }}> · {failed.length} não carregada{failed.length !== 1 ? 's' : ''}</span>}
        </div>
        <button type="button" onClick={() => window.print()}>Imprimir / Salvar PDF</button>
      </div>
      </div>

      {items.map((it, idx) => (
        <div key={it.id} className="nfse-lote-page" style={{ paddingTop: 48 }}>
          <KlavoNFSe data={it.data} municipio={it.municipio} showControls={false} />
          {idx < items.length - 1 && <div className="nfse-lote-break" />}
        </div>
      ))}

      <style>{`
        @media print {
          .nfse-lote > div:first-child { display: none !important; }
          .nfse-lote { padding: 0 !important; background: #fff !important; }
          .nfse-lote-page { padding-top: 0 !important; }
          .nfse-lote-break { break-after: page; page-break-after: always; height: 0; }
        }
      `}</style>
    </div>
  );
}

export default function PrintNfseLotePage() {
  return (
    <Suspense fallback={null}>
      <LotePrint />
    </Suspense>
  );
}
