package com.example.projectbnspumkm.ui.catalog

import android.Manifest
import android.app.AlertDialog
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.fragment.app.viewModels
import androidx.navigation.NavDeepLinkBuilder
import androidx.navigation.fragment.findNavController
import com.bumptech.glide.Glide
import com.example.projectbnspumkm.R
import com.example.projectbnspumkm.UmkmApplication
import com.example.projectbnspumkm.data.model.Product
import com.example.projectbnspumkm.databinding.FragmentDetailCatalogBinding
import com.example.projectbnspumkm.ui.MainViewModel
import com.example.projectbnspumkm.ui.catalog.CatalogFragment.Companion.CHANNEL_ID
import com.example.projectbnspumkm.ui.catalog.CatalogFragment.Companion.CHANNEL_NAME
import com.example.projectbnspumkm.ui.catalog.CatalogFragment.Companion.NOTIFICATION_ID

class DetailCatalogFragment : Fragment() {
    private var _binding: FragmentDetailCatalogBinding? = null
    private val binding get() = _binding!!

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

    private var currentProduct: Product? = null

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

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

        val id = arguments?.getInt("id") ?: 0

        viewModel.getProductById(id).observe(viewLifecycleOwner) { product ->
            product?.let {
                currentProduct = it
                binding.tvNama.text = it.name
                binding.tvDeskripsi.text = it.description
                binding.tvPrice.text = "Rp ${it.price}"

                Glide.with(this)
                    .load(it.imageUrl)
                    .placeholder(R.drawable.ic_launcher_background)
                    .into(binding.ivPicture)
            }
        }
        binding.ivDelete.setOnClickListener {
            deleteDialogCatalog()
        }

        binding.btnUpdate.setOnClickListener {
            currentProduct?.let { 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_detailCatalogFragment_to_editCatalogFragment,
                    bundle
                )
            }
        }

        binding.ivArrowBack.setOnClickListener {
            findNavController().navigateUp()
        }

        binding.btnAddToCart.setOnClickListener {
            currentProduct?.let { product ->
                viewModel.addToCart(product)
                createNotification("Keranjang ${product.name}", "Berhasil ditambahkan ke keranjang")
                Toast.makeText(context, "Ditambahkan ke keranjang", Toast.LENGTH_SHORT).show()
            }
        }
    }

    private fun createNotification(title: String, message: String) {
        val context = requireContext()

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH)
            val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            notificationManager.createNotificationChannel(channel)
        }

        val pendingIntent = NavDeepLinkBuilder(context)
            .setGraph(R.navigation.nav_graph)
            .setDestination(R.id.cartFragment)
            .createPendingIntent()

        val builder = NotificationCompat.Builder(context, CHANNEL_ID)
            .setSmallIcon(android.R.drawable.ic_dialog_info)
            .setContentTitle(title)
            .setContentText(message)
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .setContentIntent(pendingIntent)
            .setAutoCancel(true)

        with(NotificationManagerCompat.from(context)) {
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED || Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
                notify(NOTIFICATION_ID, builder.build())
            }
        }
    }

    private fun deleteDialogCatalog() {
        AlertDialog.Builder(requireContext())
            .setTitle("Hapus Menu")
            .setMessage("Apakah anda yakin ingin menghapus menu ini? ")
            .setPositiveButton("Ya") { _, _ ->
                currentProduct?.let {
                    viewModel.removeProduct(it)
                    Toast.makeText(requireContext(), "Produk berhasil dihapus", Toast.LENGTH_SHORT).show()
                    findNavController().navigateUp()
                }
            }
            .setNegativeButton("Tidak", null)
            .show()
    }

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