package com.example.projectbnspumkm.ui.catalog

import android.Manifest
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.app.ActivityCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import com.example.projectbnspumkm.R
import com.example.projectbnspumkm.UmkmApplication
import com.example.projectbnspumkm.data.repository.Resource
import com.example.projectbnspumkm.databinding.FragmentCatalogBinding
import com.example.projectbnspumkm.ui.MainViewModel

class CatalogFragment : Fragment() {

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

    companion object {
        const val CHANNEL_ID = "umkm_notification"
        const val CHANNEL_NAME = "UMKM Shop"
        const val NOTIFICATION_ID = 1
    }

    private val requestPermissionLauncher =
        registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted: Boolean ->
            if (isGranted) {
                Toast.makeText(context, "Izin notifikasi diberikan", Toast.LENGTH_SHORT).show()
            } else {
                Toast.makeText(context, "Izin notifikasi ditolak", Toast.LENGTH_SHORT).show()
            }
        }

    private val viewModel: MainViewModel by viewModels {
        MainViewModel.Factory((requireActivity().application as UmkmApplication).repository)
    }

    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)

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (ActivityCompat.checkSelfPermission(requireContext(), Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
                requestPermissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)
            }
        }

        val adapter = ProductAdapter(
            onAddToCart = { product -> viewModel.addToCart(product) },
            onDetail = { product ->
                val bundle = Bundle().apply {
                    putInt("id", product.id)
                    putString("name", product.name)
                    putString("description", product.description)
                    putDouble("price", product.price)
                    putString("imageUrl", product.imageUrl)
                }
                findNavController().navigate(R.id.action_catalogFragment_to_detailCatalogFragment, bundle)
            })

        binding.rvProducts.adapter = adapter

        viewModel.products.observe(viewLifecycleOwner) { resource ->
            when (resource) {
                is Resource.Loading -> {
                    binding.progressBar.visibility = View.VISIBLE
                }
                is Resource.Success -> {
                    binding.progressBar.visibility = View.GONE
                    adapter.submitList(resource.data)
                }
                is Resource.Error -> {
                    binding.progressBar.visibility = View.GONE
                    Toast.makeText(context, resource.message, Toast.LENGTH_SHORT).show()
                    adapter.submitList(resource.data)
                }
            }
        }

        binding.fabAddMenu.setOnClickListener {
            findNavController().navigate(R.id.action_catalogFragment_to_createCatalogFragment)
        }
    }


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