package es.verdnatura.presentation.view.feature.packaging.fragment

import android.content.Context
import android.graphics.Color
import android.graphics.drawable.Drawable
import android.os.Build
import android.util.Log.d
import android.view.View
import android.widget.ImageView
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.esafirm.imagepicker.features.ImagePickerConfig
import com.esafirm.imagepicker.features.registerImagePicker
import com.esafirm.imagepicker.model.Image
import es.verdnatura.R
import es.verdnatura.databinding.FragmentPackagingObsBinding
import es.verdnatura.domain.ConstAndValues.ENTRYNUMBERIMAGES
import es.verdnatura.domain.ConstAndValues.ENTRYOBSERVATIONS
import es.verdnatura.domain.ConstAndValues.ENTRYTYPE
import es.verdnatura.domain.ConstAndValues.SUPPLIERNAME
import es.verdnatura.presentation.base.BaseFragment
import es.verdnatura.presentation.common.*
import es.verdnatura.presentation.view.component.CustomDialog
import es.verdnatura.presentation.view.component.CustomDialogList
import es.verdnatura.presentation.view.feature.inventario.fragment.InventaryViewModel
import es.verdnatura.presentation.view.feature.packaging.adapter.ListImageAdapter
import es.verdnatura.presentation.view.feature.pasillero.model.PasillerosItemVO
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking

@Suppress("UNUSED_ANONYMOUS_PARAMETER")
class ObservFragment(
    var entryPoint: String = ""

) : BaseFragment<FragmentPackagingObsBinding, InventaryViewModel>(
    InventaryViewModel::class
) {

    private var adapterListImage: ListImageAdapter? = null
    private var listImages: MutableList<Image>? = null
    private lateinit var customDialog: CustomDialog
    private var pasillerosItemClickListener: OnPasillerosItemClickListener? = null
    private var layoutManager: LinearLayoutManager? = null
    private lateinit var customDialogList: CustomDialogList

    companion object {
        fun newInstance(entryPoint: String) = ObservFragment(entryPoint)
    }

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

    override fun onAttach(context: Context) {
        if (context is OnPasillerosItemClickListener) pasillerosItemClickListener = context
        super.onAttach(context)
    }

    override fun init() {
        customDialog = CustomDialog(requireContext())
        ma.hideBottomNavigation(View.GONE)
        setToolBar()
        setEvents()
        super.init()
    }

    private fun setToolBar() {

        binding.mainToolbar.toolbarTitle.text =
            runBlocking {
                mobileApplication.dataStoreApp.readDataStoreKey<String>(ENTRYTYPE) + ":" + mobileApplication.dataStoreApp.readDataStoreKey<String>(
                    SUPPLIERNAME
                )
            }

        val listIcons: ArrayList<ImageView> = ArrayList()
        val iconNext = ImageView(context)
        iconNext.setImageResource(R.drawable.ic_chevron_right_black_24dp)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            iconNext.tooltipText = getString(R.string.nextEntrySummary)
        }
        listIcons.add(iconNext)
        binding.mainToolbar.toolbarIcons.adapter =
            ToolBarAdapterTooltip(listIcons, object : OnOptionsSelectedListener {
                override fun onOptionsItemSelected(item: Drawable) {
                    when (item) {
                        iconNext.drawable -> {
                            lifecycleScope.launch(Dispatchers.IO) {
                                mobileApplication.dataStoreApp.editDataStoreKey(
                                    ENTRYNUMBERIMAGES, if (listImages.isNullOrEmpty()) 0 else {
                                        listImages!!.size.toString()
                                    }
                                )

                                mobileApplication.dataStoreApp.editDataStoreKey(
                                    ENTRYOBSERVATIONS,
                                    binding.observations.text.toString()
                                )
                            }

                            ma.onPasillerosItemClickListener(
                                PasillerosItemVO(title = getString(R.string.titlePackagingSummary)),
                                getString(R.string.titlePackagingSummary)
                            )
                        }

                    }

                }

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

    }

    private fun setEvents() {
        val launcher = registerImagePicker {
            for (image in it) {
                d("VERDNATURA::", "el nombre es " + image.name)
                d("VERDNATURA::", "el nombre es " + image.uri)
                //binding.imageView30.setImageURI(image.uri)
            }
            listImages = it as MutableList<Image>
            setAdapter(listImages!!)
        }

        binding.mainToolbar.backButton.setOnClickListener {
            requireActivity().onBackPressed()
        }
        binding.openPickerImages.setOnClickListener {
            val config = ImagePickerConfig {
                doneButtonText = "HECHO" // done button text
                language = "es" // Set image picker language
                arrowColor = Color.WHITE // set toolbar arrow up color
                theme = R.style.ToolPickerImage
                /*    mode = ImagePickerMode.SINGLE // default is multi image mode
                    language = "in" // Set image picker language
                    theme = R.style.ImagePickerTheme
                    // set whether pick action or camera action should return immediate result or not. Only works in single mode for image picker
                    returnMode = if (returnAfterCapture) ReturnMode.ALL else ReturnMode.NONE
                    isFolderMode = folderMode // set folder mode (false by default)
                    isIncludeVideo = includeVideo // include video (false by default)
                    isOnlyVideo = onlyVideo // include video (false by default)
                    arrowColor = Color.RED // set toolbar arrow up color
                    folderTitle = "Folder" // folder selection title
                    imageTitle = "Tap to select" // image selection title
                    doneButtonText = "DONE" // done button text
                    limit = 10 // max images can be selected (99 by default)
                    isShowCamera = true // show camera or not (true by default)
                    savePath = ImagePickerSavePath("Camera") // captured image directory name ("Camera" folder by default)
                    savePath = ImagePickerSavePath(Environment.getExternalStorageDirectory().path, isRelative = false) // can be a full path
                    excludedImages = images.toFiles() // don't show anything on this selected images
                    selectedImages = images  // original selected images, used in multi mode*/
            }
            launcher.launch(config)
        }

    }

    override fun observeViewModel() {
        with(viewModel) {

        }
    }

    fun setAdapter(list: MutableList<Image>) {
        adapterListImage =
            ListImageAdapter(list, object : OnImageUpdateClickListener {

                override fun OnImageUpdateClickListener(item: Any) {
                    d("VERDNATURA::", "Seleccionado update" + (item as Image).name)
                }
            }, object : OnImageTrashClickListener {
                override fun OnImageUpdateClickListener(item: Any) {
                    d("VERDNATURA::", "Seleccionado trash" + (item as Image).name)
                    list.remove(item)
                    adapterListImage!!.notifyDataSetChanged()
                }

            })

        binding.listImagesRecycler.adapter = adapterListImage
        layoutManager =
            LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)
        binding.listImagesRecycler.layoutManager = layoutManager
    }
}

