package com.example.projectbnspumkm.ui.catalog

import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.navigation.fragment.findNavController
import com.bumptech.glide.Glide
import com.example.projectbnspumkm.UmkmApplication
import com.example.projectbnspumkm.data.model.Product
import com.example.projectbnspumkm.databinding.FragmentCreateCatalogBinding
import com.example.projectbnspumkm.ui.MainViewModel

class CreateCatalogFragment : Fragment() {
    private var _binding: FragmentCreateCatalogBinding? = null
    private val binding get() = _binding!!

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

    private var selectedImageUri: Uri? = null

    private val pickImageLauncher = registerForActivityResult(ActivityResultContracts.GetContent()) { uri: Uri? ->
        uri?.let {
            selectedImageUri = it
            binding.ivPreview.visibility = View.VISIBLE
            Glide.with(this).load(it).into(binding.ivPreview)
        }
    }

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

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

        binding.ivArrowBack.setOnClickListener {
            findNavController().navigateUp()
        }

        binding.btnPickImage.setOnClickListener {
            pickImageLauncher.launch("image/*")
        }

        binding.btnBuat.setOnClickListener {
            val name = binding.etNama.text.toString()
            val desc = binding.etDeskripsi.text.toString()
            val price = binding.etPrice.text.toString().toDoubleOrNull() ?: 0.0
            val imageUrl = selectedImageUri?.toString() ?: ""

            if (name.isNotEmpty() && imageUrl.isNotEmpty()) {
                val newProduct = Product(
                    id = 0,
                    name = name,
                    description = desc,
                    price = price,
                    imageUrl = imageUrl
                )
                viewModel.addProduct(newProduct)
                Toast.makeText(context, "Produk Berhasil Dibuat", Toast.LENGTH_SHORT).show()
                findNavController().navigateUp()
            } else {
                Toast.makeText(context, "Nama dan Gambar wajib diisi", Toast.LENGTH_SHORT).show()
            }
        }
    }

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