package com.example.projectbnspumkm.ui.customer

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import com.example.projectbnspumkm.UmkmApplication
import com.example.projectbnspumkm.data.model.Customer
import com.example.projectbnspumkm.data.repository.Resource
import com.example.projectbnspumkm.databinding.DialogAddCustomerBinding
import com.example.projectbnspumkm.databinding.FragmentCustomerBinding
import com.example.projectbnspumkm.ui.MainViewModel
import com.google.android.material.textfield.TextInputEditText

class CustomerFragment : Fragment() {

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

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

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

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

        val adapter = CustomerAdapter { customer ->
            showCustomerOptionsDialog(customer)
        }

        binding.rvCustomers.adapter = adapter

        viewModel.customers.observe(viewLifecycleOwner) { resource ->
            when (resource) {
                is Resource.Loading -> binding.progressBar.visibility = View.VISIBLE
                is Resource.Success -> {
                    binding.progressBar.visibility = View.GONE
                    resource.data?.let { adapter.submitList(it) }
                }
                is Resource.Error -> {
                    binding.progressBar.visibility = View.GONE
                    Toast.makeText(context, resource.message, Toast.LENGTH_SHORT).show()
                    adapter.submitList(resource.data)
                }
            }
        }

        binding.fabAddCustomer.setOnClickListener {
            showAddCustomerDialog()
        }
    }

    private fun showCustomerOptionsDialog(customer: Customer) {
        val options = arrayOf("Edit", "Hapus")
        AlertDialog.Builder(requireContext())
            .setTitle("Opsi Customer")
            .setItems(options) { _, which ->
                when (which) {
                    0 -> updateCustomerDialog(customer)
                    1 -> deleteCustomerDialog(customer)
                }
            }
            .show()
    }

    private fun showAddCustomerDialog() {
        val dialogBinding = DialogAddCustomerBinding.inflate(layoutInflater)
        AlertDialog.Builder(requireContext())
            .setTitle("Tambah Customer")
            .setView(dialogBinding.root)
            .setPositiveButton("Tambah") { _, _ ->
                val name = dialogBinding.etName.text.toString()
                val email = dialogBinding.etEmail.text.toString()
                val telepon = dialogBinding.etPhone.text.toString()

                if (name.isNotEmpty() && email.isNotEmpty()) {
                    val newCustomer = Customer(
                        id = 0,
                        name = name,
                        email = email,
                        phone = telepon
                    )
                    viewModel.addCustomer(newCustomer)
                    Toast.makeText(context, "Customer berhasil ditambahkan", Toast.LENGTH_SHORT).show()
                } else {
                    Toast.makeText(context, "Nama dan email harus diisi", Toast.LENGTH_SHORT).show()
                }
            }
            .setNegativeButton("Cancel", null)
            .show()
    }

    private fun deleteCustomerDialog(customer: Customer) {
        AlertDialog.Builder(requireContext())
            .setTitle("Hapus Customer")
            .setMessage("Apa anda yakin ingin menghapus ${customer.name} dari aplikasi anda?")
            .setPositiveButton("Ya") { _, _ ->
                viewModel.removeCustomers(customer)
                Toast.makeText(requireContext(), "Data customer berhasil dihapus", Toast.LENGTH_SHORT).show()
            }
            .setNegativeButton("Tidak", null)
            .show()
    }

    private fun updateCustomerDialog(customer: Customer) {
        val dialogView = layoutInflater.inflate(com.example.projectbnspumkm.R.layout.dialog_edit_customer, null)

        val etNama = dialogView.findViewById<TextInputEditText>(com.example.projectbnspumkm.R.id.et_nama)
        val etEmail = dialogView.findViewById<TextInputEditText>(com.example.projectbnspumkm.R.id.et_email)
        val etTelepon = dialogView.findViewById<TextInputEditText>(com.example.projectbnspumkm.R.id.et_telepon)

        // Pre-fill data
        etNama.setText(customer.name)
        etEmail.setText(customer.email)
        etTelepon.setText(customer.phone)

        AlertDialog.Builder(requireContext())
            .setTitle("Edit Customer")
            .setView(dialogView)
            .setPositiveButton("Simpan") { _, _ ->
                val name = etNama.text.toString()
                val email = etEmail.text.toString()
                val telepon = etTelepon.text.toString()
                
                if (name.isNotEmpty()) {
                    val updatedCustomer = Customer(
                        id = customer.id,
                        name = name,
                        email = email,
                        phone = telepon
                    )
                    viewModel.updateCustomers(updatedCustomer)
                    Toast.makeText(requireContext(), "Data customer berhasil diupdate", Toast.LENGTH_SHORT).show()
                }
            }
            .setNegativeButton("Batal", null)
            .show()
    }

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