package com.example.tabbuy.ui.keranjang

import android.app.AlertDialog
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import com.example.tabbuy.R
import com.example.tabbuy.databinding.FragmentMetodePembayaranBinding
import com.example.tabbuy.ui.MainViewModel
import com.google.android.material.snackbar.Snackbar

class MetodePembayaranFragment : Fragment() {
    private var _binding: FragmentMetodePembayaranBinding? = null
    private val binding get() = _binding!!
    private val viewModel: MainViewModel by viewModels()

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

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

        binding.btnBack.setOnClickListener {
            findNavController().popBackStack()
        }

        binding.btnKonfirmasiBayar.setOnClickListener {
            val selectedId = binding.rgPayment.checkedRadioButtonId
            if (selectedId == -1) {
                Snackbar.make(binding.root, "Pilih metode pembayaran terlebih dahulu!", Snackbar.LENGTH_SHORT).show()
            } else {
                // Proses Pembayaran
                viewModel.clearCart()
                showSuccessDialog()
            }
        }
    }

    private fun showSuccessDialog() {
        val dialogView = LayoutInflater.from(context).inflate(R.layout.dialog_success, null)
        val alertDialog = AlertDialog.Builder(requireContext())
            .setView(dialogView)
            .setCancelable(false)
            .create()

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

        val btnSelesai = dialogView.findViewById<Button>(R.id.btnSelesai)
        btnSelesai.setOnClickListener {
            alertDialog.dismiss()
            // Kembali ke katalog/home setelah sukses
            findNavController().navigate(R.id.katalogFragment)
        }

        alertDialog.show()
    }

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