import api from '@/lib/api';
import type { NFSeData, MunicipioInfo } from '@/components/KlavoNFSe';

const TAX_REGIME_LABELS: Record<number, string> = {
  1: 'Simples Nacional',
  2: 'Simples Nacional — excesso de sublimite',
  3: 'Regime Normal',
  4: 'Lucro Real',
  5: 'Lucro Presumido',
  6: 'MEI',
};

type Muni = { municipio: string; uf: string };

// Lookups do IBGE e do cadastro de clientes são compartilhados entre as notas
// de um lote: o mesmo município/cliente se repete muito.
const ibgeCache = new Map<string, Promise<Muni>>();
const clientCache = new Map<string, Promise<any>>();

function ibgeMunicipio(code?: string): Promise<Muni> {
  if (!code) return Promise.resolve({ municipio: '—', uf: '—' });
  if (!ibgeCache.has(code)) {
    ibgeCache.set(code, (async () => {
      try {
        const r = await fetch(`https://servicodados.ibge.gov.br/api/v1/localidades/municipios/${code}`);
        if (!r.ok) throw new Error();
        const d = await r.json();
        return { municipio: d.nome ?? code, uf: d.microrregiao?.mesorregiao?.UF?.sigla ?? '—' };
      } catch {
        return { municipio: code, uf: '—' };
      }
    })());
  }
  return ibgeCache.get(code)!;
}

function loadClient(id: string): Promise<any> {
  if (!clientCache.has(id)) clientCache.set(id, api.get(`/clients/${id}`).then((r) => r.data));
  return clientCache.get(id)!;
}

function mapStatus(s: string): NFSeData['status'] {
  if (s === 'issued')    return 'autorizada';
  if (s === 'cancelled') return 'cancelada';
  if (s === 'error')     return 'rejeitada';
  return 'processando';
}

export interface NfsePrintItem {
  id: string;
  data: NFSeData;
  municipio: MunicipioInfo;
}

// Monta os dados do DANFSe (modelo Klavo) de uma nota já carregada.
export async function buildNfsePrint(inv: any, tenant: any): Promise<NfsePrintItem> {
  const client = await loadClient(inv.clientId);

  const [tenantMuni, clientMuni, serviceMuni] = await Promise.all([
    ibgeMunicipio(tenant.ibgeCode),
    ibgeMunicipio(client.ibgeCode),
    ibgeMunicipio(inv.serviceCityCode),
  ]);

  const issAmount = Number(inv.issAmount ?? 0);
  const aliquota  = Number(inv.issAliquota ?? 0);

  const data: NFSeData = {
    numero:     inv.nfseNumber ?? String(inv.rpsNumber ?? '—'),
    dpsNumero:  String(inv.rpsNumber ?? '—'),
    dpsSerie:   inv.rpsSerie ?? 'RPS',
    emissaoEm:  inv.nfseIssuedAt ?? inv.createdAt ?? new Date().toISOString(),
    chaveAcesso: inv.nfseVerifyCode ?? inv.nfseNumber ?? String(inv.rpsNumber ?? '—'),
    autorizacao: inv.nfseNumber ?? String(inv.rpsNumber ?? '—'),
    status:      mapStatus(inv.status),

    municipioEmissor: {
      municipio: tenantMuni.municipio,
      uf: tenant.uf ?? tenantMuni.uf,
    },
    naturezaOperacao: 'Tributação no município',
    regimeTributario: TAX_REGIME_LABELS[tenant.taxRegime ?? 1] ?? 'Regime Normal',

    prestador: {
      nome: tenant.name,
      cnpj: tenant.document?.replace(/\D/g, '').length !== 11 ? tenant.document : undefined,
      cpf:  tenant.document?.replace(/\D/g, '').length === 11 ? tenant.document : undefined,
      inscricaoMunicipal: tenant.municipalInscription ?? undefined,
      endereco: {
        logradouro: '—',
        municipio:  tenantMuni.municipio,
        uf:         tenant.uf ?? tenantMuni.uf,
        cep:        '—',
      },
      telefone: tenant.phone   ?? undefined,
      email:    tenant.email   ?? undefined,
      simplesNacional: tenant.simpleNational,
      logoUrl:  tenant.logoUrl ?? undefined,
    },

    tomador: {
      nome: client.name,
      cnpj: client.document?.replace(/\D/g, '').length !== 11 ? client.document : undefined,
      cpf:  client.document?.replace(/\D/g, '').length === 11 ? client.document : undefined,
      inscricaoMunicipal: client.municipalInscription ?? undefined,
      endereco: {
        logradouro: [client.address, client.addressNumber].filter(Boolean).join(', ') || '—',
        bairro:     client.neighborhood ?? undefined,
        municipio:  clientMuni.municipio,
        uf:         client.uf ?? clientMuni.uf,
        cep:        client.zipCode ?? '—',
      },
      telefone: client.phone  ?? undefined,
      email:    client.email  ?? undefined,
    },

    servico: {
      codigoLc116:      inv.serviceListItem ?? '—',
      codigoMunicipal:  inv.cnaeCode ?? undefined,
      itemListaServico: inv.serviceListItem ?? '—',
      descricao:        inv.discrimination ?? '—',
      municipioPrestacao: { municipio: serviceMuni.municipio, uf: serviceMuni.uf, pais: 'Brasil' },
      municipioIssqn:     { municipio: serviceMuni.municipio, uf: serviceMuni.uf },
      paisResultado: 'Brasil',
    },

    tributacao: {
      situacaoIssqn:          'Operação tributável',
      baseCalculo:            Number(inv.serviceAmount),
      aliquota,
      issqnApurado:           issAmount,
      retencaoIssqn:          inv.issRetained ? 'retido' : 'nao_retido',
      deducoes:               0,
      descontoIncondicionado: 0,
      irrf:           0,
      inss:           0,
      contribSociais: 0,
    },

    totais: {
      valorServico:      Number(inv.serviceAmount),
      issqnRetido:       inv.issRetained ? issAmount : undefined,
      retencoesFederais: 0,
      valorLiquido:      Number(inv.netAmount ?? inv.serviceAmount),
      tributosAproxFederais:  0,
      tributosAproxEstaduais: 0,
      tributosAproxMunicipais: issAmount,
    },

    urlVerificacao: inv.nfseUrl ?? undefined,
  };

  let portalHost = 'www.nfse.gov.br';
  if (inv.nfseUrl) {
    try { portalHost = new URL(inv.nfseUrl).hostname; } catch { /* mantém o portal nacional */ }
  }

  const municipio: MunicipioInfo = {
    nome:       tenantMuni.municipio,
    uf:         tenant.uf ?? tenantMuni.uf,
    secretaria: 'Secretaria Municipal de Fazenda',
    telefone:   '—',
    portal:     portalHost,
  };

  return { id: inv.id, data, municipio };
}
