package com.example.projectbnspumkm.ui.cart

import android.annotation.SuppressLint
import android.app.Dialog
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import com.example.projectbnspumkm.R
import com.example.projectbnspumkm.UmkmApplication
import com.example.projectbnspumkm.databinding.FragmentCartBinding
import com.example.projectbnspumkm.ui.MainViewModel

class CartFragment : Fragment() {

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

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

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

    @SuppressLint("SetTextI18n")
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        val adapter = CartAdapter { item ->
            viewModel.removeFromCart(item)
            Toast.makeText(requireContext(), "Item ${item.productName} keranjang berhasil dihapus", Toast.LENGTH_SHORT).show()
        }
        binding.rvCart.adapter = adapter

        viewModel.cartItems.observe(viewLifecycleOwner) { items ->
            adapter.submitList(items)
            val total = items.sumOf { it.productPrice * it.quantity }
            binding.tvTotalPrice.text = "Rp $total"
        }

        binding.btnCheckout.setOnClickListener {
            if (viewModel.cartItems.value.isNullOrEmpty()) {
                Toast.makeText(context, "Tidak ada cart item", Toast.LENGTH_SHORT).show()
            } else {
                showDialogPembayaranBerhasil()
                Toast.makeText(context, "Pembayaran berhasil", Toast.LENGTH_LONG).show()
            }
        }
    }

        private fun showDialogPembayaranBerhasil() {
            val dialog = Dialog(requireContext())

            dialog.setContentView(R.layout.dialog_pembayaran_berhasil)

            dialog.setCancelable(false)

            val btnOk = dialog.findViewById<Button>(R.id.btn_ok)

            btnOk.setOnClickListener {
                dialog.dismiss()
            }

            dialog.window?.setBackgroundDrawableResource(android.R.color.transparent)

            dialog.show()
        }

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