package com.gestoreasy.ui.reports

import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.gestoreasy.MobileApp
import com.gestoreasy.R
import com.gestoreasy.databinding.ActivityReportsBinding
import com.gestoreasy.network.ApiClient
import com.gestoreasy.repository.CommissionRepository
import kotlinx.coroutines.launch
import java.util.Calendar

/**
 * Activity para relatórios de vendas e comissões
 */
class ReportsActivity : AppCompatActivity() {
    private lateinit var binding: ActivityReportsBinding
    private lateinit var app: MobileApp
    private lateinit var commissionRepository: CommissionRepository
    
    private var vendedorId: Long = -1
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityReportsBinding.inflate(layoutInflater)
        setContentView(binding.root)
        
        setSupportActionBar(binding.toolbar)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        
        app = MobileApp.get(this)
        commissionRepository = CommissionRepository(app.database.commissionDao())
        
        vendedorId = intent.getLongExtra("vendedor_id", -1)
        
        if (vendedorId == -1L) {
            Toast.makeText(this, "Vendedor não identificado", Toast.LENGTH_SHORT).show()
            finish()
            return
        }
        
        setupViews()
        loadReports()
    }
    
    private fun setupViews() {
        // Filtros de período
        binding.btnFilterToday.setOnClickListener {
            filterByPeriod(Period.TODAY)
        }
        
        binding.btnFilterWeek.setOnClickListener {
            filterByPeriod(Period.WEEK)
        }
        
        binding.btnFilterMonth.setOnClickListener {
            filterByPeriod(Period.MONTH)
        }
        
        binding.btnFilterYear.setOnClickListener {
            filterByPeriod(Period.YEAR)
        }
        
        // Configurar RecyclerView
        binding.recyclerCommissions.layoutManager = LinearLayoutManager(this)
    }
    
    private fun loadReports() {
        lifecycleScope.launch {
            try {
                // Carregar resumo de comissões
                val summaryResponse = ApiClient.api.getCommissionsSummary(vendedorId)
                if (summaryResponse.isSuccessful && summaryResponse.body()?.success == true) {
                    val summary = summaryResponse.body()?.data
                    displaySummary(summary)
                }
                
                // Carregar comissões
                val commissionsResponse = ApiClient.api.getCommissions(vendedorId)
                if (commissionsResponse.isSuccessful && commissionsResponse.body()?.success == true) {
                    val commissions = commissionsResponse.body()?.data ?: emptyList()
                    displayCommissions(commissions)
                }
            } catch (e: Exception) {
                Toast.makeText(this@ReportsActivity, "Erro ao carregar relatórios: ${e.message}", Toast.LENGTH_SHORT).show()
            }
        }
    }
    
    private fun displaySummary(summary: com.gestoreasy.network.CommissionSummary?) {
        summary?.let {
            binding.textTotalPedidos.text = "Total de Pedidos: ${it.total_pedidos}"
            binding.textTotalVendas.text = "Total de Vendas: R$ ${String.format("%.2f", it.total_vendas)}"
            binding.textTotalComissao.text = "Total de Comissão: R$ ${String.format("%.2f", it.total_comissao)}"
            binding.textComissaoPaga.text = "Comissão Paga: R$ ${String.format("%.2f", it.comissao_paga)}"
            binding.textComissaoPendente.text = "Comissão Pendente: R$ ${String.format("%.2f", it.comissao_pendente)}"
        }
    }
    
    private fun displayCommissions(commissions: List<com.gestoreasy.database.entities.Commission>) {
        val adapter = CommissionsAdapter()
        binding.recyclerCommissions.adapter = adapter
        adapter.submitList(commissions)
    }
    
    private fun filterByPeriod(period: Period) {
        val calendar = Calendar.getInstance()
        val endDate = calendar.timeInMillis
        
        when (period) {
            Period.TODAY -> {
                calendar.set(Calendar.HOUR_OF_DAY, 0)
                calendar.set(Calendar.MINUTE, 0)
                calendar.set(Calendar.SECOND, 0)
            }
            Period.WEEK -> {
                calendar.add(Calendar.DAY_OF_WEEK, -7)
            }
            Period.MONTH -> {
                calendar.add(Calendar.MONTH, -1)
            }
            Period.YEAR -> {
                calendar.add(Calendar.YEAR, -1)
            }
        }
        
        val startDate = calendar.timeInMillis
        
        lifecycleScope.launch {
            try {
                val response = ApiClient.api.getCommissions(vendedorId, startDate, endDate)
                if (response.isSuccessful && response.body()?.success == true) {
                    val commissions = response.body()?.data ?: emptyList()
                    displayCommissions(commissions)
                }
            } catch (e: Exception) {
                Toast.makeText(this@ReportsActivity, "Erro ao filtrar: ${e.message}", Toast.LENGTH_SHORT).show()
            }
        }
    }
    
    enum class Period {
        TODAY, WEEK, MONTH, YEAR
    }
}

