package com.gestoreasy.ui.goals

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.database.entities.Goal
import com.gestoreasy.databinding.ActivityGoalsBinding
import com.gestoreasy.network.ApiClient
import com.gestoreasy.repository.GoalRepository
import kotlinx.coroutines.launch

/**
 * Activity para visualização de metas e objetivos
 */
class GoalsActivity : AppCompatActivity() {
    private lateinit var binding: ActivityGoalsBinding
    private lateinit var app: MobileApp
    private lateinit var goalRepository: GoalRepository
    private lateinit var adapter: GoalsAdapter
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityGoalsBinding.inflate(layoutInflater)
        setContentView(binding.root)
        
        setSupportActionBar(binding.toolbar)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        
        app = MobileApp.get(this)
        goalRepository = GoalRepository(app.database.goalDao())
        adapter = GoalsAdapter { goal -> onGoalClick(goal) }
        
        setupRecyclerView()
        loadGoals()
    }
    
    private fun setupRecyclerView() {
        binding.recyclerGoals.layoutManager = LinearLayoutManager(this)
        binding.recyclerGoals.adapter = adapter
        
        binding.fabSync.setOnClickListener {
            loadGoals()
        }
    }
    
    private fun loadGoals() {
        lifecycleScope.launch {
            try {
                // Buscar do servidor
                val response = ApiClient.api.getGoals()
                if (response.isSuccessful && response.body()?.success == true) {
                    val goals = response.body()?.data ?: emptyList()
                    
                    // Salvar localmente
                    goals.forEach { goal ->
                        goalRepository.insertOrUpdate(goal)
                    }
                    
                    // Carregar do banco local
                    val localGoals = goalRepository.getActive()
                    adapter.submitList(localGoals)
                } else {
                    // Carregar do banco local
                    val localGoals = goalRepository.getActive()
                    adapter.submitList(localGoals)
                }
            } catch (e: Exception) {
                Toast.makeText(this@GoalsActivity, "Erro ao carregar metas: ${e.message}", Toast.LENGTH_SHORT).show()
                
                // Carregar do banco local em caso de erro
                val localGoals = goalRepository.getActive()
                adapter.submitList(localGoals)
            }
        }
    }
    
    private fun onGoalClick(goal: Goal) {
        // Abrir detalhes da meta
        // TODO: Navegar para GoalDetailActivity
    }
}

/**
 * Adapter para lista de metas
 */
class GoalsAdapter(
    private val onItemClick: (Goal) -> Unit
) : androidx.recyclerview.widget.ListAdapter<Goal, GoalsAdapter.GoalViewHolder>(GoalDiffCallback()) {
    
    override fun onCreateViewHolder(parent: android.view.ViewGroup, viewType: Int): GoalViewHolder {
        val binding = com.gestoreasy.databinding.ItemGoalBinding.inflate(
            android.view.LayoutInflater.from(parent.context),
            parent,
            false
        )
        return GoalViewHolder(binding, onItemClick)
    }
    
    override fun onBindViewHolder(holder: GoalViewHolder, position: Int) {
        holder.bind(getItem(position))
    }
    
    class GoalViewHolder(
        private val binding: com.gestoreasy.databinding.ItemGoalBinding,
        private val onItemClick: (Goal) -> Unit
    ) : androidx.recyclerview.widget.RecyclerView.ViewHolder(binding.root) {
        
        fun bind(goal: Goal) {
            binding.textGoalTitle.text = goal.titulo
            binding.textGoalType.text = goal.tipo.uppercase()
            
            goal.descricao?.let {
                binding.textGoalDescription.text = it
                binding.textGoalDescription.visibility = android.view.View.VISIBLE
            } ?: run {
                binding.textGoalDescription.visibility = android.view.View.GONE
            }
            
            val progress = if (goal.valor_meta > 0) {
                (goal.valor_atual / goal.valor_meta * 100).toInt().coerceIn(0, 100)
            } else {
                0
            }
            
            binding.progressGoal.progress = progress
            binding.textGoalProgress.text = 
                "R$ ${String.format("%.2f", goal.valor_atual)} / R$ ${String.format("%.2f", goal.valor_meta)} ($progress%)"
            
            // Data início e fim
            val dateFormat = java.text.SimpleDateFormat("dd/MM/yyyy", java.util.Locale("pt", "BR"))
            binding.root.findViewById<android.widget.TextView>(R.id.textGoalStartDate)?.text = 
                "Início: ${dateFormat.format(java.util.Date(goal.data_inicio))}"
            binding.root.findViewById<android.widget.TextView>(R.id.textGoalEndDate)?.text = 
                "Fim: ${dateFormat.format(java.util.Date(goal.data_fim))}"
            
            binding.root.setOnClickListener { onItemClick(goal) }
        }
    }
    
    class GoalDiffCallback : androidx.recyclerview.widget.DiffUtil.ItemCallback<Goal>() {
        override fun areItemsTheSame(oldItem: Goal, newItem: Goal): Boolean {
            return oldItem.id == newItem.id
        }
        
        override fun areContentsTheSame(oldItem: Goal, newItem: Goal): Boolean {
            return oldItem == newItem
        }
    }
}

