package com.gestoreasy.ui.order

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import android.view.LayoutInflater
import androidx.recyclerview.widget.LinearLayoutManager
import com.gestoreasy.MobileApp
import com.gestoreasy.R
import com.gestoreasy.database.entities.*
import com.gestoreasy.databinding.ActivityOrderDetailBinding
import com.gestoreasy.network.ApiClient
import com.gestoreasy.repository.*
import com.gestoreasy.repository.OrderItemRepository
import com.gestoreasy.services.PdfService
import com.gestoreasy.services.WhatsAppService
import com.gestoreasy.ui.order.OrderItemsAdapter
import kotlinx.coroutines.launch

/**
 * Activity para visualização e gestão de pedido
 * Inclui geração de PDF e envio por WhatsApp
 */
class OrderDetailActivity : AppCompatActivity() {
    private lateinit var binding: ActivityOrderDetailBinding
    private lateinit var app: MobileApp
    private lateinit var orderRepository: OrderRepository
    private lateinit var orderItemRepository: OrderItemRepository
    private lateinit var clientRepository: ClientRepository
    private lateinit var productRepository: ProductRepository
    private lateinit var pdfService: PdfService
    private lateinit var whatsAppService: WhatsAppService
    
    private var orderId: Long = -1
    private lateinit var order: Order
    private var client: Client? = null
    private val items = mutableListOf<OrderItem>()
    private val products = mutableMapOf<Long, Product>()
    private lateinit var itemsAdapter: OrderItemsAdapter
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityOrderDetailBinding.inflate(layoutInflater)
        setContentView(binding.root)
        
        setSupportActionBar(binding.toolbar)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        
        app = MobileApp.get(this)
        orderRepository = OrderRepository(app.database.orderDao())
        orderItemRepository = OrderItemRepository(app.database.orderItemDao())
        clientRepository = ClientRepository(app.database.clientDao())
        productRepository = ProductRepository(app.database.productDao())
        pdfService = PdfService(this)
        whatsAppService = WhatsAppService(this)
        
        orderId = intent.getLongExtra("order_id", -1)
        
        if (orderId == -1L) {
            Toast.makeText(this, "Pedido inválido", Toast.LENGTH_SHORT).show()
            finish()
            return
        }
        
        setupViews()
        loadOrder()
    }
    
    private fun setupViews() {
        // Configurar RecyclerView
        itemsAdapter = OrderItemsAdapter(products)
        binding.recyclerOrderItems.layoutManager = LinearLayoutManager(this)
        binding.recyclerOrderItems.adapter = itemsAdapter
        
        // Botão gerar PDF
        binding.btnGeneratePdf.setOnClickListener {
            generatePdf()
        }
        
        // Botão enviar por WhatsApp
        binding.btnSendWhatsApp.setOnClickListener {
            sendWhatsApp()
        }
        
        // Botão compartilhar
        binding.btnShare.setOnClickListener {
            shareOrder()
        }
    }
    
    private fun loadOrder() {
        lifecycleScope.launch {
            try {
                order = orderRepository.getById(orderId) ?: run {
                    Toast.makeText(this@OrderDetailActivity, "Pedido não encontrado", Toast.LENGTH_SHORT).show()
                    finish()
                    return@launch
                }
                
                // Carregar cliente
                order.client_id?.let { clientId ->
                    client = clientRepository.getById(clientId)
                }
                
                // Carregar itens do pedido (primeiro do banco local, depois do servidor se necessário)
                items.clear()
                val localItems = orderItemRepository.getByOrderId(orderId)
                if (localItems.isEmpty()) {
                    // Buscar do servidor
                    try {
                        val apiResponse = ApiClient.api.getOrderItems(orderId)
                        if (apiResponse.isSuccessful && apiResponse.body()?.success == true) {
                            val serverItems = apiResponse.body()?.data ?: emptyList()
                            orderItemRepository.insertAll(serverItems)
                            items.addAll(serverItems)
                        }
                    } catch (e: Exception) {
                        // Falha ao buscar do servidor, usar itens locais (vazios)
                    }
                } else {
                    items.addAll(localItems)
                }
                
                // Carregar produtos
                items.forEach { item ->
                    item.product_id?.let { productId ->
                        productRepository.getById(productId)?.let { product ->
                            products[productId] = product
                        }
                    }
                }
                
                itemsAdapter = OrderItemsAdapter(products)
                binding.recyclerOrderItems.adapter = itemsAdapter
                itemsAdapter.submitList(items)
                
                displayOrder()
            } catch (e: Exception) {
                Toast.makeText(this@OrderDetailActivity, "Erro ao carregar pedido: ${e.message}", Toast.LENGTH_SHORT).show()
            }
        }
    }
    
    private fun displayOrder() {
        supportActionBar?.title = "Pedido ${order.numero}"
        binding.textOrderNumber.text = "Pedido: ${order.numero}"
        binding.textOrderTotal.text = "Total: R$ ${String.format("%.2f", order.total)}"
        client?.let {
            binding.textClientName.text = "Cliente: ${it.nome}"
        }
    }
    
    private fun generatePdf() {
        lifecycleScope.launch {
            try {
                val pdfFile = pdfService.generateOrderPdf(order, client, items, products)
                
                // Abrir PDF
                val intent = Intent(Intent.ACTION_VIEW).apply {
                    setDataAndType(Uri.fromFile(pdfFile), "application/pdf")
                    flags = Intent.FLAG_ACTIVITY_NO_HISTORY
                }
                
                if (intent.resolveActivity(packageManager) != null) {
                    startActivity(intent)
                } else {
                    Toast.makeText(this@OrderDetailActivity, "Nenhum visualizador de PDF encontrado", Toast.LENGTH_SHORT).show()
                }
            } catch (e: Exception) {
                Toast.makeText(this@OrderDetailActivity, "Erro ao gerar PDF: ${e.message}", Toast.LENGTH_SHORT).show()
            }
        }
    }
    
    private fun sendWhatsApp() {
        lifecycleScope.launch {
            try {
                if (!whatsAppService.isWhatsAppInstalled()) {
                    Toast.makeText(this@OrderDetailActivity, "WhatsApp não está instalado", Toast.LENGTH_SHORT).show()
                    return@launch
                }
                
                val pdfFile = pdfService.generateOrderPdf(order, client, items, products)
                val phoneNumber = client?.telefone?.replace(Regex("[^0-9]"), "") ?: ""
                
                if (phoneNumber.isEmpty()) {
                    Toast.makeText(this@OrderDetailActivity, "Cliente não possui telefone cadastrado", Toast.LENGTH_SHORT).show()
                    return@launch
                }
                
                whatsAppService.sendOrderPdf(phoneNumber, pdfFile)
            } catch (e: Exception) {
                Toast.makeText(this@OrderDetailActivity, "Erro ao enviar por WhatsApp: ${e.message}", Toast.LENGTH_SHORT).show()
            }
        }
    }
    
    private fun shareOrder() {
        lifecycleScope.launch {
            try {
                val pdfFile = pdfService.generateOrderPdf(order, client, items, products)
                
                val intent = Intent(Intent.ACTION_SEND).apply {
                    type = "application/pdf"
                    putExtra(Intent.EXTRA_STREAM, Uri.fromFile(pdfFile))
                    putExtra(Intent.EXTRA_TEXT, "Pedido ${order.numero} - Total: R$ ${String.format("%.2f", order.total)}")
                }
                
                startActivity(Intent.createChooser(intent, "Compartilhar pedido"))
            } catch (e: Exception) {
                Toast.makeText(this@OrderDetailActivity, "Erro ao compartilhar: ${e.message}", Toast.LENGTH_SHORT).show()
            }
        }
    }
}

