package com.example.bnsptest.ui

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.bnsptest.databinding.FragmentCartBinding

class CartFragment : Fragment() {

    private var _binding: FragmentCartBinding? = null
    private val binding get() = _binding!!

    private val viewModel: ProductViewModel by viewModels {
        ViewModelFactory(requireContext())
    }

    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 = { product -> viewModel.increaseQuantity(product) },
            onDecrease = { product -> viewModel.decreaseQuantity(product) }
        )

        binding.rvCart.apply {
            layoutManager = LinearLayoutManager(requireContext())
            this.adapter = adapter
        }

        viewModel.cartProducts.observe(viewLifecycleOwner) { items ->
            adapter.submitList(items?.toMutableList())
            binding.btnCheckout.isEnabled = items?.isNotEmpty() == true
        }

        binding.btnCheckout.setOnClickListener {
            viewModel.checkout()
            Toast.makeText(requireContext(), "Checkout complete. Items deleted from cart.", Toast.LENGTH_SHORT).show()
        }
    }

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