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 com.example.bnsptest.databinding.FragmentCatalogBinding
import com.example.bnsptest.utils.NotificationHelper

class CatalogFragment : Fragment() {

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

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

    private lateinit var notificationHelper: NotificationHelper

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

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

        notificationHelper = NotificationHelper(requireContext())

        val adapter = ProductAdapter { product ->
            viewModel.addToCart(product)
            notificationHelper.showCartNotification(product.name)
            Toast.makeText(requireContext(), "${product.name} added to cart", Toast.LENGTH_SHORT)
                .show()
        }

        binding.rvProducts.adapter = adapter

        viewModel.catalogProducts.observe(viewLifecycleOwner) { products ->
            adapter.submitList(products)
        }
    }

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