package com.example.tabbuy.ui.admin

import android.app.AlertDialog
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.tabbuy.adapter.PelangganAdapter
import com.example.tabbuy.data.local.entity.PelangganEntity
import com.example.tabbuy.databinding.FragmentPelangganListBinding
import com.example.tabbuy.ui.MainViewModel

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

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

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

        val adapter = PelangganAdapter(
            onDeleteClick = { pelanggan ->
                showDeleteConfirmDialog(pelanggan)
            }
        )

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

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

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

        // Load data awal
        viewModel.loadPelanggan()
    }

    private fun showDeleteConfirmDialog(pelanggan: PelangganEntity) {
        AlertDialog.Builder(requireContext())
            .setTitle("Hapus Pelanggan")
            .setMessage("Apakah Anda yakin ingin menghapus pelanggan '${pelanggan.nama}'?")
            .setPositiveButton("Hapus") { _, _ ->
                viewModel.deletePelanggan(pelanggan)
                Toast.makeText(context, "Pelanggan berhasil dihapus", Toast.LENGTH_SHORT).show()
            }
            .setNegativeButton("Batal", null)
            .show()
    }

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