package com.example.projectbnspumkm.ui.catalog

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 com.example.projectbnspumkm.UmkmApplication
import com.example.projectbnspumkm.data.model.Product
import com.example.projectbnspumkm.databinding.FragmentEditCatalogBinding
import com.example.projectbnspumkm.ui.MainViewModel
import com.google.android.material.bottomsheet.BottomSheetDialogFragment

class EditCatalogFragment : BottomSheetDialogFragment() {
    private var _binding: FragmentEditCatalogBinding? = null
    private val binding get() = _binding!!

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

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

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


        val id = arguments?.getInt("id") ?: 0
        val name = arguments?.getString("name") ?: ""
        val desc = arguments?.getString("description") ?: ""
        val price = arguments?.getDouble("price") ?: 0.0
        val imageUrl = arguments?.getString("imageUrl") ?: ""

        binding.etNama.setText(name)
        binding.etDeskripsi.setText(desc)
        binding.etPrice.setText(price.toString())

        binding.ivArrowBack.setOnClickListener {
            dismiss()
        }

        binding.btnUpdate.setOnClickListener {
            val updatedName = binding.etNama.text.toString()
            val updatedDesc = binding.etDeskripsi.text.toString()
            val updatedPrice = binding.etPrice.text.toString().toDoubleOrNull() ?: 0.0

            if (updatedName.isNotEmpty() && updatedDesc.isNotEmpty()) {
                val updateProduct = Product(
                    id = id,
                    name = updatedName,
                    description = updatedDesc,
                    price = updatedPrice,
                    imageUrl = imageUrl
                )

                viewModel.updateProduct(updateProduct)
                Toast.makeText(requireContext(), "Katalog berhasil diperbarui", Toast.LENGTH_SHORT).show()
                dismiss()
            } else {
                Toast.makeText(requireContext(), "Semua field harus diisi", Toast.LENGTH_SHORT).show()
            }
        }
    }

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