package com.gestoreasy.services

import android.content.Context
import com.gestoreasy.database.entities.Order
import com.gestoreasy.database.entities.OrderItem
import com.gestoreasy.database.entities.Client
import com.gestoreasy.database.entities.Product
// Nota: Requer dependência: implementation "com.itextpdf:itext7-core:7.2.5"
// Alternativa: usar AndroidPdfViewer ou gerar HTML e converter
import com.itextpdf.kernel.pdf.PdfDocument
import com.itextpdf.kernel.pdf.PdfWriter
import com.itextpdf.layout.Document
import com.itextpdf.layout.element.Paragraph
import com.itextpdf.layout.element.Table
import com.itextpdf.layout.element.Cell
import com.itextpdf.layout.property.TextAlignment
import com.itextpdf.layout.property.UnitValue
import java.io.File
import java.text.SimpleDateFormat
import java.util.*

/**
 * Serviço para geração de PDF de pedido no layout de NF-e
 */
class PdfService(private val context: Context) {
    
    fun generateOrderPdf(
        order: Order,
        client: Client?,
        items: List<OrderItem>,
        products: Map<Long, Product>
    ): File {
        val fileName = "pedido_${order.numero}_${System.currentTimeMillis()}.pdf"
        val file = File(context.getExternalFilesDir(null), fileName)
        
        val writer = PdfWriter(file)
        val pdfDoc = PdfDocument(writer)
        val document = Document(pdfDoc)
        
        // Cabeçalho
        document.add(createHeader())
        
        // Dados da empresa (simulado - deve vir do backend)
        document.add(createCompanyInfo())
        
        // Dados do cliente
        if (client != null) {
            document.add(createClientInfo(client))
        }
        
        // Dados do pedido
        document.add(createOrderInfo(order))
        
        // Tabela de itens
        document.add(createItemsTable(items, products))
        
        // Totais
        document.add(createTotals(order))
        
        // Rodapé
        document.add(createFooter())
        
        document.close()
        
        return file
    }
    
    private fun createHeader(): Paragraph {
        val header = Paragraph("PEDIDO DE VENDA")
            .setFontSize(18f)
            .setBold()
            .setTextAlignment(TextAlignment.CENTER)
            .setMarginBottom(20f)
        return header
    }
    
    private fun createCompanyInfo(): Paragraph {
        // TODO: Buscar dados da empresa do backend
        val companyInfo = """
            EMPRESA EXEMPLO LTDA
            CNPJ: 12.345.678/0001-90
            Endereço: Rua Exemplo, 123 - Centro
            CEP: 12345-678 - Cidade/UF
            Telefone: (11) 1234-5678
        """.trimIndent()
        
        return Paragraph(companyInfo)
            .setFontSize(10f)
            .setMarginBottom(15f)
    }
    
    private fun createClientInfo(client: Client): Paragraph {
        val clientInfo = buildString {
            append("CLIENTE:\n")
            append("Nome: ${client.nome}\n")
            if (client.cpf_cnpj != null) {
                append("CPF/CNPJ: ${client.cpf_cnpj}\n")
            }
            if (client.endereco != null) {
                append("Endereço: ${client.endereco}\n")
            }
            if (client.cidade != null && client.estado != null) {
                append("Cidade/UF: ${client.cidade}/${client.estado}\n")
            }
            if (client.cep != null) {
                append("CEP: ${client.cep}\n")
            }
            if (client.telefone != null) {
                append("Telefone: ${client.telefone}\n")
            }
        }
        
        return Paragraph(clientInfo)
            .setFontSize(10f)
            .setMarginBottom(15f)
    }
    
    private fun createOrderInfo(order: Order): Paragraph {
        val dateFormat = SimpleDateFormat("dd/MM/yyyy HH:mm", Locale("pt", "BR"))
        val orderInfo = buildString {
            append("PEDIDO Nº: ${order.numero}\n")
            append("Data: ${dateFormat.format(Date(order.data))}\n")
            append("Status: ${order.status.uppercase()}\n")
            if (order.observacoes != null) {
                append("Observações: ${order.observacoes}\n")
            }
        }
        
        return Paragraph(orderInfo)
            .setFontSize(10f)
            .setMarginBottom(15f)
    }
    
    private fun createItemsTable(items: List<OrderItem>, products: Map<Long, Product>): Table {
        val table = Table(UnitValue.createPercentArray(floatArrayOf(5f, 30f, 10f, 10f, 10f, 15f)))
            .useAllAvailableWidth()
        
        // Cabeçalho da tabela
        table.addHeaderCell(Cell().add(Paragraph("Item").setBold()))
        table.addHeaderCell(Cell().add(Paragraph("Descrição").setBold()))
        table.addHeaderCell(Cell().add(Paragraph("Qtd").setBold()).setTextAlignment(TextAlignment.CENTER))
        table.addHeaderCell(Cell().add(Paragraph("Unit.").setBold()).setTextAlignment(TextAlignment.RIGHT))
        table.addHeaderCell(Cell().add(Paragraph("Desc.").setBold()).setTextAlignment(TextAlignment.RIGHT))
        table.addHeaderCell(Cell().add(Paragraph("Total").setBold()).setTextAlignment(TextAlignment.RIGHT))
        
        // Itens
        items.forEachIndexed { index, item ->
            val product = products[item.product_id]
            val description = product?.nome ?: "Produto não encontrado"
            
            table.addCell(Cell().add(Paragraph("${index + 1}")))
            table.addCell(Cell().add(Paragraph(description)))
            table.addCell(Cell().add(Paragraph(String.format("%.2f", item.quantidade))).setTextAlignment(TextAlignment.CENTER))
            table.addCell(Cell().add(Paragraph(String.format("R$ %.2f", item.preco_unitario))).setTextAlignment(TextAlignment.RIGHT))
            table.addCell(Cell().add(Paragraph(String.format("R$ %.2f", item.desconto))).setTextAlignment(TextAlignment.RIGHT))
            table.addCell(Cell().add(Paragraph(String.format("R$ %.2f", item.total))).setTextAlignment(TextAlignment.RIGHT))
        }
        
        return table
    }
    
    private fun createTotals(order: Order): Paragraph {
        val totals = buildString {
            append("\n")
            append("SUBTOTAL: R$ ${String.format("%.2f", order.subtotal)}\n")
            if (order.desconto > 0) {
                append("DESCONTO: R$ ${String.format("%.2f", order.desconto)}\n")
            }
            append("TOTAL: R$ ${String.format("%.2f", order.total)}\n")
        }
        
        return Paragraph(totals)
            .setFontSize(12f)
            .setBold()
            .setTextAlignment(TextAlignment.RIGHT)
            .setMarginTop(20f)
    }
    
    private fun createFooter(): Paragraph {
        val footer = """
            
            
            Este documento é uma cópia do pedido de venda.
            Gerado em: ${SimpleDateFormat("dd/MM/yyyy HH:mm:ss", Locale("pt", "BR")).format(Date())}
        """.trimIndent()
        
        return Paragraph(footer)
            .setFontSize(8f)
            .setTextAlignment(TextAlignment.CENTER)
            .setMarginTop(30f)
    }
}

