package com.example.tabbuy.ui.katalog

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 android.widget.TextView
import androidx.appcompat.widget.SearchView
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.tabbuy.MainActivity
import com.example.tabbuy.R
import com.example.tabbuy.adapter.ProdukAdapter
import com.example.tabbuy.data.local.entity.ProdukEntity
import com.example.tabbuy.databinding.FragmentKatalogBinding
import com.example.tabbuy.ui.MainViewModel

class KatalogFragment : Fragment() {
    private var _binding: FragmentKatalogBinding? = null
    private val binding get() = _binding!!
    private val viewModel: MainViewModel by activityViewModels()

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

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

        val adapter = ProdukAdapter(
            onProductClick = { produk ->
                // 1. Simpan ke ViewModel agar URI tetap valid di session ini
                viewModel.selectProduk(produk)
                
                // 2. Kirim Bundle sebagai cadangan navigasi
                val bundle = Bundle().apply {
                    putInt("id", produk.id)
                    putString("nama", produk.nama)
                    putInt("harga", produk.harga)
                    putString("deskripsi", produk.deskripsi)
                    putString("gambar", produk.gambar)
                }
                findNavController().navigate(R.id.action_katalogFragment_to_detailProdukFragment, bundle)
            },
            onAddToCart = { produk ->
                viewModel.addToCart(produk)
                showSuccessDialog(produk.nama)
                (activity as? MainActivity)?.sendNotification("Berhasil!", "${produk.nama} masuk keranjang.")
            },
            onEditClick = { produk ->
                val bundle = Bundle().apply { putParcelable("produk", produk) }
                findNavController().navigate(R.id.action_katalogFragment_to_tambahProdukFragment, bundle)
            },
            onDeleteClick = { produk -> showDeleteConfirmDialog(produk) }
        )

        binding.rvProduk.apply {
            layoutManager = LinearLayoutManager(context)
            this.adapter = adapter
        }

        viewModel.allProduk.observe(viewLifecycleOwner) { produkList ->
            adapter.setData(produkList)
            binding.rvProduk.visibility = if (produkList.isEmpty()) View.GONE else View.VISIBLE
            binding.layoutEmpty.visibility = if (produkList.isEmpty()) View.VISIBLE else View.GONE
        }

        binding.searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
            override fun onQueryTextSubmit(query: String?): Boolean = false
            override fun onQueryTextChange(newText: String?): Boolean {
                viewModel.searchProduk(newText.orEmpty())
                return true
            }
        })

        binding.fabAddProduk.setOnClickListener {
            findNavController().navigate(R.id.tambahProdukFragment)
        }
    }

    private fun showDeleteConfirmDialog(produk: ProdukEntity) {
        AlertDialog.Builder(requireContext())
            .setTitle("Hapus Produk")
            .setMessage("Hapus '${produk.nama}'?")
            .setPositiveButton("Hapus") { _, _ -> viewModel.deleteProduk(produk) }
            .setNegativeButton("Batal", null)
            .show()
    }

    private fun showSuccessDialog(namaProduk: String) {
        val dialogView = LayoutInflater.from(context).inflate(R.layout.dialog_success_add, null)
        val alertDialog = AlertDialog.Builder(context).setView(dialogView).create()
        alertDialog.window?.setBackgroundDrawableResource(android.R.color.transparent)
        dialogView.findViewById<TextView>(R.id.tvSubMessage).text = "$namaProduk masuk keranjang."
        dialogView.findViewById<Button>(R.id.btnOk).setOnClickListener { alertDialog.dismiss() }
        dialogView.findViewById<Button>(R.id.btnGoToCart).setOnClickListener {
            alertDialog.dismiss()
            findNavController().navigate(R.id.keranjangFragment)
        }
        alertDialog.show()
    }

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