import android.app.Activity.RESULT_OK
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import android.view.View.*
import android.view.inputmethod.EditorInfo
import android.widget.ImageView
import androidx.annotation.RequiresApi
import androidx.core.net.toUri
import androidx.recyclerview.widget.LinearLayoutManager
import es.verdnatura.R
import es.verdnatura.databinding.FragmentPhotosBinding
import es.verdnatura.domain.ConstAndValues.WAREHOUSEFK
import es.verdnatura.domain.toast
import es.verdnatura.presentation.base.BaseFragment
import es.verdnatura.presentation.common.OnOptionsSelectedListener
import es.verdnatura.presentation.common.ToolBarAdapterTooltip
import es.verdnatura.presentation.common.itemScanValue
import es.verdnatura.presentation.common.loadUrl
import es.verdnatura.presentation.view.feature.articulo.fragment.ItemCardViewModel
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.*

class PhotosFragment(
    var title: String,
    var uriImage: Uri?
) : BaseFragment<FragmentPhotosBinding, ItemCardViewModel>(
    ItemCardViewModel::class
) {
    private val PICK_IMAGE_REQUEST = 1
    private val REQUEST_IMAGE_CAPTURE = 2
    private val imageUri: Uri? = null
    private var originalItem: Number = 0

    override fun getLayoutId(): Int = R.layout.fragment_photos

    companion object {
        fun newInstance(title: String, uriImage: String) = PhotosFragment(title, uriImage.toUri())
    }

    @RequiresApi(Build.VERSION_CODES.O)
    override fun init() {
        binding.mainToolbar.toolbarTitle.text = title
        setEvents()
        setToolBar()
        setImage()
        super.init()
    }

    private fun setImage() {
        if (uriImage != null) {
            binding.itemcardImage.setImageURI(uriImage)
        }
    }

    @RequiresApi(Build.VERSION_CODES.O)
    private fun setToolBar() {

        binding.mainToolbar.toolbarSubtitle.visibility = VISIBLE
        binding.mainToolbar.toolbarIcons.visibility = VISIBLE
        binding.mainToolbar.backButton.visibility = VISIBLE

        val listIcons: ArrayList<ImageView> = ArrayList()
        val iconPhoto = ImageView(context)
        val iconSend = ImageView(context)
        iconSend.setImageResource(R.drawable.ic_image_upload)
        iconPhoto.setImageResource(R.drawable.ef_ic_camera_white)

        iconPhoto.tooltipText = getTooltip(R.drawable.ef_ic_camera_white)
        iconSend.tooltipText = getTooltip(R.drawable.ic_image_upload)

        listIcons.add(iconPhoto)
        listIcons.add(iconSend)

        binding.mainToolbar.toolbarIcons.adapter =
            ToolBarAdapterTooltip(listIcons, object : OnOptionsSelectedListener {
                override fun onOptionsItemSelected(item: Drawable) {

                    when (item) {
                        iconPhoto.drawable -> getPhoto()
                        iconSend.drawable -> upLoadPhoto()
                    }

                }
            })
        binding.mainToolbar.toolbarIcons.layoutManager =
            LinearLayoutManager(requireContext(), LinearLayoutManager.HORIZONTAL, false)
    }

    private fun getPhoto() {
        pickImage()
    }

    private fun setEvents() {
        binding.mainToolbar.backButton.setOnClickListener {
            requireActivity().onBackPressed()
        }

        binding.editItemFk.setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || actionId == 0 || actionId == 5) {
                if (!binding.editItemFk.text.toString().isEmpty()) {

                    originalItem = itemScanValue(
                        binding.editItemFk.text.toString(),
                        "buy",
                        "more"
                    ).toString().toLong()

                    try {
                        viewModel.getItemCard(
                            originalItem,  mobileApplication.dataStoreApp.readDataStoreKey(WAREHOUSEFK)
                        )

                    } catch (Ex: Exception) {
                        ma.messageWithSound(Ex.message.toString(), true, true)
                    }
                }
                binding.editItemFk.setText("")
                ma.hideKeyboard(binding.editItemFk)
                return@setOnEditorActionListener true
            }
            false
        }

        binding.editItemFk.requestFocus()

    }

    override fun observeViewModel() {

        with(viewModel) {
            responseinsert.observe(viewLifecycleOwner) {
                if (it.isError) {
                    ma.messageWithSound(
                        it.errorMessage + getString(R.string.user) + title,
                        isError = true,
                        true
                    )

                } else {
                    ma.messageWithSound(
                        getString(R.string.itemUpdated),
                        isError = it.isError,
                        true
                    )
                }

            }
            itemcard.observe(viewLifecycleOwner) {
                if (it.isError) {
                    ma.messageWithSound(it.errorMessage, true, false)
                } else {
                    if (it.id != 0) {
                        binding.itemData.text = "${it.id}: ${it.longName}"
                        if (!it.urlImage200.isNullOrEmpty()) {
                            binding.itemcardOriginal.visibility = VISIBLE
                            binding.itemcardOriginal.loadUrl(it.urlImage200)
                        }
                    } else {
                        ma.messageWithSound(
                            getString(R.string.itemNotFound),
                            true,
                            false,
                            getString(R.string.noResults)
                        )

                    }

                }
            }

        }

    }

    private fun upLoadPhoto() {

        if (binding.itemData.text.isNullOrEmpty()) {
            getString(R.string.messageUploadItem).toast(requireContext()).show()
        } else {
            val drawable = binding.itemcardImage.drawable
            if (drawable is BitmapDrawable) {
                val bitmap = drawable.bitmap
                viewModel.uploadPhoto(
                    itemFK = originalItem,
                    urlImage = saveBitmapAsTempFile(requireContext(), bitmap)
                )
            }
        }
    }

    fun saveBitmapAsTempFile(context: Context, bitmap: Bitmap): String {
        val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date())
        val fileName = "IMG_$timeStamp.jpg"

        val storageDir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES)
        val tempFile = File.createTempFile(fileName, null, storageDir)

        return try {
            val fileOutputStream = FileOutputStream(tempFile)
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream)
            fileOutputStream.close()
            tempFile.absolutePath
        } catch (e: IOException) {
            e.printStackTrace()
            ""
        }
    }

    private fun pickImage() {
        val pickIntent = Intent(Intent.ACTION_PICK)
        pickIntent.type = "image/*"
        val captureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        val chooserIntent = Intent.createChooser(pickIntent, getString(R.string.selectImage))
        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, arrayOf(captureIntent))
        startActivityForResult(chooserIntent, PICK_IMAGE_REQUEST)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK) {
            if (data != null && data.data != null) {
                // Imagen seleccionada desde la galería
                binding.itemcardImage.setImageURI(data.data)
            } else {
                // Imagen cámara
                val uri = saveBitmapAsTempFile(
                    requireContext(),
                    data?.extras?.get("data") as Bitmap
                ).toUri()
                binding.itemcardImage.setImageURI(uri)

            }
        }
    }
}
