package com.example.orderly.ui

import android.Manifest
import android.content.ContentValues
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.MediaStore
import android.view.LayoutInflater
import android.view.View
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.activity.viewModels
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.ui.setupWithNavController
import com.example.orderly.data.entity.Product
import com.example.orderly.databinding.ActivityMainBinding
import com.example.orderly.databinding.BottomSheetAddProductBinding
import com.google.android.material.bottomsheet.BottomSheetDialog
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.WorkManager
import androidx.work.Data
import com.example.orderly.R
import com.example.orderly.ui.notification.NotificationWorker

class MainActivity : AppCompatActivity() {
    private lateinit var binding: ActivityMainBinding
    private val viewModel: OrderLyViewModel by viewModels {
        OrderLyViewModelFactory((application as OrderLyApplication).repository)
    }
    private var imageUri: Uri? = null
    private var bottomSheetBinding: BottomSheetAddProductBinding? = null

    private val pickImageLauncher =
        registerForActivityResult(ActivityResultContracts.GetContent()) { uri ->
            uri?.let {
                imageUri = it
                bottomSheetBinding?.ivPreview?.setImageURI(it)
            }
        }

    private val takePhotoLauncher =
        registerForActivityResult(ActivityResultContracts.TakePicture()) { success ->
            if (success) {
                imageUri?.let {
                    bottomSheetBinding?.ivPreview?.setImageURI(it)
                }
            }
        }

    private val requestPermissionLauncher =
        registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted ->
            if (isGranted) {
                openCamera()
            } else {
                Toast.makeText(this, "Izin kamera ditolak", Toast.LENGTH_SHORT).show()
            }
        }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS)
                != PackageManager.PERMISSION_GRANTED
            ) {
                requestPermissions(
                    arrayOf(Manifest.permission.POST_NOTIFICATIONS),
                    100
                )
            }
        }

        val navHostFragment =
            supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment
        val navController = navHostFragment.navController

        binding.bottomNavigation.setupWithNavController(navController)

        navController.addOnDestinationChangedListener { _, destination, _ ->
            when (destination.id) {
                R.id.nav_home, R.id.nav_cart -> {
                    binding.bottomAppBar.visibility = View.VISIBLE
                    binding.fabCart.visibility = View.VISIBLE
                }
                else -> {
                    binding.bottomAppBar.visibility = View.GONE
                    binding.fabCart.visibility = View.GONE
                }
            }
        }

        binding.fabCart.setOnClickListener {
            showAddProductBottomSheet()
        }
    }

    private fun showAddProductBottomSheet() {
        val dialog = BottomSheetDialog(this)
        bottomSheetBinding =
            BottomSheetAddProductBinding.inflate(LayoutInflater.from(this))
        dialog.setContentView(bottomSheetBinding!!.root)

        bottomSheetBinding!!.cvAddPhoto.setOnClickListener {
            showImageSourceDialog()
        }

        bottomSheetBinding!!.btnSaveProduct.setOnClickListener {

            val name = bottomSheetBinding!!.etProductName.text.toString().trim()
            val priceStr = bottomSheetBinding!!.etProductPrice.text.toString().trim()
            val desc = bottomSheetBinding!!.etProductDesc.text.toString().trim()
            val type = if (bottomSheetBinding!!.rbFood.isChecked) "Makanan" else "Minuman"

            if (name.isEmpty() || priceStr.isEmpty()) {
                Toast.makeText(this, "Mohon lengkapi data", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            val price = priceStr.toDoubleOrNull() ?: 0.0
            val image = imageUri?.toString() ?: ""

            val product = Product(
                name = name,
                description = desc,
                price = price,
                imageUrl = image,
                category = type
            )

            viewModel.addProduct(product)

            val data = Data.Builder()
                .putString("title", "Menu Baru")
                .putString("message", name)
                .build()

            val workRequest =
                OneTimeWorkRequestBuilder<NotificationWorker>()
                    .setInputData(data)
                    .build()

            WorkManager.getInstance(this).enqueue(workRequest)

            Toast.makeText(this, "Produk ditambahkan", Toast.LENGTH_SHORT).show()
            dialog.dismiss()
        }

        dialog.show()
    }

    private fun showImageSourceDialog() {
        val options = arrayOf("Galeri", "Kamera")
        AlertDialog.Builder(this)
            .setTitle("Pilih Sumber Gambar")
            .setItems(options) { _, which ->
                when (which) {
                    0 -> pickImageLauncher.launch("image/*")
                    1 -> checkCameraPermission()
                }
            }
            .show()
    }

    private fun checkCameraPermission() {
        when {
            ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.CAMERA
            ) == PackageManager.PERMISSION_GRANTED -> {
                openCamera()
            }
            else -> {
                requestPermissionLauncher.launch(Manifest.permission.CAMERA)
            }
        }
    }

    private fun openCamera() {
        val contentValues = ContentValues().apply {
            put(MediaStore.Images.Media.TITLE, "New Product Photo")
            put(MediaStore.Images.Media.DESCRIPTION, "From Camera")
        }
        imageUri = contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues)
        takePhotoLauncher.launch(imageUri!!)
    }
}
