package com.gestoreasy.ui

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.gestoreasy.MobileApp
import com.gestoreasy.R
import com.gestoreasy.databinding.FragmentDashboardBinding
import com.gestoreasy.repository.GoalRepository
import com.gestoreasy.repository.OrderRepository
import com.gestoreasy.ui.animations.AnimationUtils
import kotlinx.coroutines.launch

/**
 * Fragment do Dashboard principal
 */
class DashboardFragment : Fragment() {
    private var _binding: FragmentDashboardBinding? = null
    private val binding get() = _binding!!
    
    private lateinit var app: MobileApp
    private lateinit var orderRepository: OrderRepository
    private lateinit var goalRepository: GoalRepository
    
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentDashboardBinding.inflate(inflater, container, false)
        return binding.root
    }
    
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        
        app = MobileApp.get(requireContext())
        orderRepository = OrderRepository(app.database.orderDao())
        goalRepository = GoalRepository(app.database.goalDao())
        
        setupViews()
        loadData()
        
        // Animar entrada
        AnimationUtils.fadeIn(binding.root, 300)
    }
    
    private fun setupViews() {
        binding.btnNewClient.setOnClickListener {
            startActivity(Intent(requireContext(), com.gestoreasy.ui.client.ClientFormActivity::class.java))
        }
        
        binding.btnNewOrder.setOnClickListener {
            // TODO: Abrir tela de criação de pedido
        }
        
        binding.btnSync.setOnClickListener {
            syncData()
        }
        
        binding.btnViewAllGoals.setOnClickListener {
            startActivity(Intent(requireContext(), com.gestoreasy.ui.goals.GoalsActivity::class.java))
        }
    }
    
    private fun loadData() {
        lifecycleScope.launch {
            try {
                // Carregar pedidos de hoje
                val today = System.currentTimeMillis()
                val startOfDay = today - (today % (24 * 60 * 60 * 1000))
                val orders = orderRepository.getAll().filter { it.created_at >= startOfDay }
                
                binding.textOrdersToday.text = orders.size.toString()
                
                val totalSales = orders.sumOf { it.total }
                binding.textSalesToday.text = "R$ ${String.format("%.2f", totalSales)}"
                
                // Animar números
                AnimationUtils.scaleIn(binding.textOrdersToday, 200)
                AnimationUtils.scaleIn(binding.textSalesToday, 200)
                
                // Carregar metas ativas
                val goals = goalRepository.getActive().take(3)
                // TODO: Configurar adapter para RecyclerView
                
            } catch (e: Exception) {
                // Tratar erro
            }
        }
    }
    
    private fun syncData() {
        lifecycleScope.launch {
            try {
                AnimationUtils.pulse(binding.btnSync, 500, false)
                app.syncManager.syncAll(force = true)
                loadData() // Recarregar dados após sincronização
            } catch (e: Exception) {
                AnimationUtils.shake(binding.btnSync)
            }
        }
    }
    
    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}
