package com.example.orderly.ui.cart

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.viewModels
import androidx.navigation.fragment.findNavController
import com.example.orderly.ui.OrderLyApplication
import com.example.orderly.R
import com.example.orderly.databinding.FragmentCartBinding
import com.example.orderly.ui.OrderLyViewModel
import com.example.orderly.ui.OrderLyViewModelFactory
import java.text.NumberFormat
import java.util.*

class CartFragment : Fragment() {
    private var _binding: FragmentCartBinding? = null
    private val binding get() = _binding!!
    private val viewModel: OrderLyViewModel by viewModels {
        OrderLyViewModelFactory((requireActivity().application as OrderLyApplication).repository)
    }

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

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

        val adapter = CartAdapter(
            onIncrease = { item -> viewModel.updateCartQuantity(item, item.quantity + 1) },
            onDecrease = { item -> viewModel.updateCartQuantity(item, item.quantity - 1) }
        )
        binding.rvCart.adapter = adapter

        viewModel.cartItems.observe(viewLifecycleOwner) { items ->
            adapter.submitList(items)
        }

        viewModel.totalPrice.observe(viewLifecycleOwner) { total ->
            val formatter = NumberFormat.getCurrencyInstance(Locale("id", "ID"))
            binding.tvTotalPrice.text = formatter.format(total)
        }

        binding.btnCheckout.setOnClickListener {
            findNavController().navigate(R.id.action_nav_cart_to_checkoutFragment)
        }
    }

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