package com.example.orderly.ui.detail

import android.content.Context
import android.content.Intent
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.viewModels
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import com.bumptech.glide.Glide
import com.example.orderly.R
import com.example.orderly.data.entity.Product
import com.example.orderly.databinding.BottomSheetAddProductBinding
import com.example.orderly.databinding.FragmentDetailBinding
import com.example.orderly.ui.OrderLyApplication
import com.example.orderly.ui.OrderLyViewModel
import com.example.orderly.ui.OrderLyViewModelFactory
import com.google.android.material.bottomsheet.BottomSheetDialog
import java.io.File
import java.io.FileOutputStream
import java.text.NumberFormat
import java.util.*

class DetailFragment : Fragment() {
    private var _binding: FragmentDetailBinding? = null
    private val binding get() = _binding!!
    private val args: DetailFragmentArgs by navArgs()
    private val viewModel: OrderLyViewModel by viewModels {
        OrderLyViewModelFactory(
            (requireActivity().application as OrderLyApplication).repository
        )
    }
    private var currentProduct: Product? = null
    private var imageUri: Uri? = null

    private val pickImageLauncher =
        registerForActivityResult(ActivityResultContracts.GetContent()) { uri ->
            uri?.let {
                // Simpan foto ke internal storage agar permanen
                val savedUri = saveImageToInternalStorage(it)
                imageUri = savedUri
                
                // Update tampilan preview
                Glide.with(this).load(savedUri).into(binding.ivDetailProduct)
            }
        }

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

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

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

        binding.btnEdit.setOnClickListener {
            currentProduct?.let { showEditDialog(it) }
        }

        viewModel.filteredProducts.observe(viewLifecycleOwner) { list ->
            val product = list.find { it.id == args.productId }
            product?.let { setupUI(it) }
        }

        binding.btnOrderNow.setOnClickListener {
            currentProduct?.let {
                viewModel.addToCart(it)
                Toast.makeText(requireContext(), "Berhasil ditambahkan ke keranjang", Toast.LENGTH_SHORT).show()
                findNavController().navigateUp()
            }
        }
    }

    private fun setupUI(product: Product) {
        currentProduct = product

        binding.tvDetailName.text = product.name
        binding.tvDetailDesc.text = product.description

        val formatter = NumberFormat.getCurrencyInstance(Locale("id", "ID")).apply {
            maximumFractionDigits = 0
        }
        binding.btnDetailPrice.text = formatter.format(product.price)

        Glide.with(this)
            .load(product.imageUrl)
            .placeholder(android.R.drawable.ic_menu_gallery)
            .into(binding.ivDetailProduct)
    }

    private fun saveImageToInternalStorage(uri: Uri): Uri? {
        return try {
            val inputStream = requireContext().contentResolver.openInputStream(uri)
            val fileName = "product_${System.currentTimeMillis()}.jpg"
            val file = File(requireContext().filesDir, fileName)
            val outputStream = FileOutputStream(file)
            
            inputStream?.use { input ->
                outputStream.use { output ->
                    input.copyTo(output)
                }
            }
            Uri.fromFile(file)
        } catch (e: Exception) {
            e.printStackTrace()
            null
        }
    }

    private fun showEditDialog(product: Product) {
        val dialog = BottomSheetDialog(requireContext())
        val dialogBinding = BottomSheetAddProductBinding.inflate(layoutInflater)
        dialog.setContentView(dialogBinding.root)

        dialogBinding.etProductName.setText(product.name)
        dialogBinding.etProductPrice.setText(product.price.toInt().toString())
        dialogBinding.etProductDesc.setText(product.description)

        if (product.category == "Makanan") {
            dialogBinding.rbFood.isChecked = true
        } else {
            dialogBinding.rbDrink.isChecked = true
        }

        dialogBinding.cvAddPhoto.setOnClickListener {
            pickImageLauncher.launch("image/*")
        }

        dialogBinding.btnSaveProduct.setOnClickListener {
            val updated = product.copy(
                name = dialogBinding.etProductName.text.toString(),
                price = dialogBinding.etProductPrice.text.toString().toDoubleOrNull() ?: 0.0,
                description = dialogBinding.etProductDesc.text.toString(),
                category = if (dialogBinding.rbFood.isChecked) "Makanan" else "Minuman",
                imageUrl = imageUri?.toString() ?: product.imageUrl
            )
            viewModel.updateProduct(updated)
            Toast.makeText(requireContext(), "Produk diupdate", Toast.LENGTH_SHORT).show()
            dialog.dismiss()
        }
        dialog.show()
    }

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