package com.example.kasirapp

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.kasirapp.data.AppDatabase
import com.example.kasirapp.data.Product
import kotlinx.coroutines.launch

class ManageMenuActivity : AppCompatActivity() {

    private lateinit var rvMenu: RecyclerView
    private lateinit var menuAdapter: MenuAdapter
    private var productList = mutableListOf<Product>()
    private val db by lazy { AppDatabase.getDatabase(this) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_manage_menu)

        rvMenu = findViewById(R.id.rv_menu)
        rvMenu.layoutManager = LinearLayoutManager(this)
        menuAdapter = MenuAdapter(productList, this::showAddEditDialog, this::deleteProduct)
        rvMenu.adapter = menuAdapter

        findViewById<View>(R.id.fab_add_menu).setOnClickListener {
            showAddEditDialog(null)
        }

        loadProductsFromDb()
    }

    private fun loadProductsFromDb() {
        lifecycleScope.launch {
            val products = db.productDao().getAllProducts()
            productList.clear()
            productList.addAll(products)
            menuAdapter.notifyDataSetChanged()
        }
    }

    private fun showAddEditDialog(product: Product?) {
        val dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_add_edit_menu, null)
        val etMenuName = dialogView.findViewById<EditText>(R.id.et_menu_name)
        val etMenuPrice = dialogView.findViewById<EditText>(R.id.et_menu_price)
        val etMenuStock = dialogView.findViewById<EditText>(R.id.et_menu_stock)
        val spinnerCategory = dialogView.findViewById<Spinner>(R.id.spinner_menu_category)

        val categories = arrayOf("Makanan", "Minuman", "Snack")
        val adapter = ArrayAdapter(this, android.R.layout.simple_spinner_dropdown_item, categories)
        spinnerCategory.adapter = adapter

        product?.let {
            etMenuName.setText(it.name)
            etMenuPrice.setText(it.price.toString())
            etMenuStock.setText(it.stock.toString())
            spinnerCategory.setSelection(categories.indexOf(it.category).coerceAtLeast(0))
        }

        AlertDialog.Builder(this)
            .setTitle(if (product == null) "Tambah Menu" else "Edit Menu")
            .setView(dialogView)
            .setPositiveButton("Simpan") { _, _ ->
                val name = etMenuName.text.toString()
                val price = etMenuPrice.text.toString().toIntOrNull() ?: 0
                val stock = etMenuStock.text.toString().toIntOrNull() ?: 0
                val category = spinnerCategory.selectedItem.toString()

                if (name.isNotBlank()) {
                    lifecycleScope.launch {
                        if (product == null) {
                            // Add new product
                            val newProduct = Product(name = name, price = price, category = category, stock = stock, imageResName = "ic_launcher_background")
                            db.productDao().insert(newProduct)
                        } else {
                            // Edit existing product
                            val updatedProduct = product.copy(name = name, price = price, stock = stock, category = category)
                            db.productDao().updateProduct(updatedProduct)
                        }
                        // Refresh list from DB
                        loadProductsFromDb()
                    }
                }
            }
            .setNegativeButton("Batal", null)
            .show()
    }

    private fun deleteProduct(product: Product) {
        AlertDialog.Builder(this)
            .setTitle("Hapus Menu")
            .setMessage("Yakin ingin menghapus item \"${product.name}\"?")
            .setPositiveButton("Hapus") { _, _ ->
                lifecycleScope.launch {
                    db.productDao().delete(product)
                    loadProductsFromDb() // Refresh list
                }
            }
            .setNegativeButton("Batal", null)
            .show()
    }

    class MenuAdapter(
        private val menuList: List<Product>,
        private val onEdit: (Product) -> Unit,
        private val onDelete: (Product) -> Unit
    ) :
        RecyclerView.Adapter<MenuAdapter.MenuViewHolder>() {

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MenuViewHolder {
            val view = LayoutInflater.from(parent.context).inflate(R.layout.item_menu, parent, false)
            return MenuViewHolder(view)
        }

        override fun onBindViewHolder(holder: MenuViewHolder, position: Int) {
            val menuItem = menuList[position]
            holder.bind(menuItem, onEdit, onDelete)
        }

        override fun getItemCount(): Int = menuList.size

        class MenuViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
            private val tvMenuName: TextView = itemView.findViewById(R.id.tv_menu_name)
            private val tvMenuPrice: TextView = itemView.findViewById(R.id.tv_menu_price)
            private val btnEdit: Button = itemView.findViewById(R.id.btn_edit_menu)
            private val btnDelete: Button = itemView.findViewById(R.id.btn_delete_menu)

            fun bind(product: Product, onEdit: (Product) -> Unit, onDelete: (Product) -> Unit) {
                tvMenuName.text = product.name
                tvMenuPrice.text = "Rp ${product.price}"

                btnEdit.setOnClickListener { onEdit(product) }
                btnDelete.setOnClickListener { onDelete(product) }
            }
        }
    }
}
