package com.example.tabbuy.ui.katalog

import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
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.tabbuy.MainActivity
import com.example.tabbuy.data.local.entity.ProdukEntity
import com.example.tabbuy.databinding.FragmentTambahProdukBinding
import com.example.tabbuy.ui.MainViewModel
import com.google.android.material.snackbar.Snackbar

class TambahProdukFragment : Fragment() {
    private var _binding: FragmentTambahProdukBinding? = null
    private val binding get() = _binding!!
    
    private val viewModel: MainViewModel by activityViewModels()
    private var imageUri: Uri? = null

    private val selectImageLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
        if (result.resultCode == Activity.RESULT_OK) {
            val selectedUri = result.data?.data
            if (selectedUri != null) {
                try {
                    // Minta izin akses permanen (hanya untuk ACTION_OPEN_DOCUMENT)
                    val takeFlags: Int = Intent.FLAG_GRANT_READ_URI_PERMISSION
                    requireContext().contentResolver.takePersistableUriPermission(selectedUri, takeFlags)
                } catch (e: Exception) {
                    e.printStackTrace()
                }
                
                imageUri = selectedUri
                // Gunakan Glide untuk preview agar lebih stabil
                Glide.with(this).load(imageUri).into(binding.ivPreview)
                binding.ivPreview.visibility = View.VISIBLE
                binding.layoutPlaceholder.visibility = View.GONE
            }
        }
    }

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

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

        val produk = arguments?.getParcelable<ProdukEntity>("produk")

        if (produk != null) {
            binding.tvTitle.text = "Edit Produk"
            binding.btnSimpanProduk.text = "Simpan Perubahan"
            binding.etNamaProduk.setText(produk.nama)
            binding.etHargaProduk.setText(produk.harga.toString())
            binding.etDeskripsi.setText(produk.deskripsi)
            
            if (produk.gambar.isNotEmpty()) {
                imageUri = Uri.parse(produk.gambar)
                // PERBAIKAN: Gunakan Glide, JANGAN gunakan setImageURI(imageUri)
                // Glide akan menangani SecurityException jika izin file lama sudah hilang
                Glide.with(this)
                    .load(imageUri)
                    .placeholder(android.R.drawable.ic_menu_gallery)
                    .error(android.R.drawable.ic_menu_report_image)
                    .into(binding.ivPreview)
                
                binding.ivPreview.visibility = View.VISIBLE
                binding.layoutPlaceholder.visibility = View.GONE
            }
        }

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

        binding.cardPilihGambar.setOnClickListener {
            val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
                addCategory(Intent.CATEGORY_OPENABLE)
                type = "image/*"
            }
            selectImageLauncher.launch(intent)
        }

        binding.btnSimpanProduk.setOnClickListener {
            val nama = binding.etNamaProduk.text.toString()
            val hargaStr = binding.etHargaProduk.text.toString()
            val deskripsi = binding.etDeskripsi.text.toString()

            if (nama.isNotEmpty() && hargaStr.isNotEmpty()) {
                if (produk != null) {
                    val produkUpdate = produk.copy(
                        nama = nama,
                        harga = hargaStr.toInt(),
                        deskripsi = deskripsi,
                        gambar = imageUri?.toString() ?: produk.gambar
                    )
                    viewModel.updateProduk(produkUpdate)
                    (activity as? MainActivity)?.sendNotification("Produk Diperbarui", "Data '$nama' berhasil diperbarui.")
                } else {
                    val produkBaru = ProdukEntity(
                        nama = nama,
                        harga = hargaStr.toInt(),
                        deskripsi = deskripsi,
                        gambar = imageUri?.toString() ?: ""
                    )
                    viewModel.addProduk(produkBaru)
                    (activity as? MainActivity)?.sendNotification("Produk Baru!", "Produk '$nama' berhasil ditambahkan.")
                }
                findNavController().popBackStack()
            } else {
                Snackbar.make(binding.root, "Nama dan Harga wajib diisi!", Snackbar.LENGTH_SHORT).show()
            }
        }
    }

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