package com.example.tabbuy.ui.keranjang

import android.app.AlertDialog
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.tabbuy.R
import com.example.tabbuy.adapter.KeranjangAdapter
import com.example.tabbuy.data.local.entity.KeranjangEntity
import com.example.tabbuy.databinding.FragmentKeranjangBinding
import com.example.tabbuy.ui.MainViewModel
import java.text.NumberFormat
import java.util.Locale

class KeranjangFragment : Fragment() {
    private var _binding: FragmentKeranjangBinding? = null
    private val binding get() = _binding!!
    
    // Gunakan activityViewModels agar berbagi data dengan KatalogFragment
    private val viewModel: MainViewModel by activityViewModels()

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        _binding = FragmentKeranjangBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        val adapter = KeranjangAdapter(
            onUpdateClick = { newItem ->
                viewModel.updateKeranjang(newItem)
            },
            onDeleteClick = { keranjangItem ->
                showDeleteConfirmDialog(keranjangItem)
            }
        )

        binding.rvKeranjang.apply {
            layoutManager = LinearLayoutManager(context)
            this.adapter = adapter
        }

        viewModel.allKeranjang.observe(viewLifecycleOwner) { keranjangList ->
            adapter.setData(keranjangList)
            
            // HITUNG TOTAL HARGA
            var totalHarga = 0
            keranjangList.forEach { item ->
                totalHarga += (item.harga * item.jumlah)
            }
            
            // Format Mata Uang Indonesia (Tanpa Desimal)
            val localeID = Locale("in", "ID")
            val formatRupiah = NumberFormat.getCurrencyInstance(localeID)
            formatRupiah.maximumFractionDigits = 0 // Menghilangkan ,00
            
            binding.tvTotal.text = formatRupiah.format(totalHarga)
            
            // LOGIKA UI: Tampilkan Placeholder jika kosong
            if (keranjangList.isNullOrEmpty()) {
                binding.rvKeranjang.visibility = View.GONE
                binding.layoutSummary.visibility = View.GONE
                binding.layoutEmpty.visibility = View.VISIBLE
            } else {
                binding.rvKeranjang.visibility = View.VISIBLE
                binding.layoutSummary.visibility = View.VISIBLE
                binding.layoutEmpty.visibility = View.GONE
            }
        }

        binding.btnBayar.setOnClickListener {
            findNavController().navigate(R.id.action_keranjangFragment_to_metodePembayaranFragment)
        }
    }

    private fun showDeleteConfirmDialog(item: KeranjangEntity) {
        val builder = AlertDialog.Builder(requireContext())
        builder.setTitle("Hapus Item")
        builder.setMessage("Apakah Anda yakin ingin menghapus ${item.namaProduk}?")
        builder.setPositiveButton("Hapus") { dialog, _ ->
            viewModel.removeFromCart(item)
            dialog.dismiss()
        }
        builder.setNegativeButton("Batal", null)
        builder.show()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}
