package bou.amine.apps.readerforselfossv2.android.fragments

import android.content.Context
import android.graphics.Color
import android.graphics.drawable.Drawable
import android.graphics.drawable.GradientDrawable
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.View.GONE
import android.view.View.VISIBLE
import android.view.ViewGroup
import bou.amine.apps.readerforselfossv2.android.HomeActivity
import bou.amine.apps.readerforselfossv2.android.R
import bou.amine.apps.readerforselfossv2.android.sendSilentlyWithAcraWithName
import bou.amine.apps.readerforselfossv2.repository.Repository
import bou.amine.apps.readerforselfossv2.utils.getHtmlDecoded
import bou.amine.apps.readerforselfossv2.utils.getIcon
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import com.google.android.material.chip.Chip
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.kodein.di.DI
import org.kodein.di.DIAware
import org.kodein.di.android.x.closestDI
import org.kodein.di.instance


class FilterSheetFragment : BottomSheetDialogFragment(), DIAware {

    override val di: DI by closestDI()
    private val repository: Repository by instance()

    private var selectedChip: Chip? = null

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        val binding =
            bou.amine.apps.readerforselfossv2.android.databinding.FilterFragmentBinding.inflate(
                inflater,
                container,
                false
            )

        val context: Context? = context

        val tagGroup = binding.tagsGroup
        val sourceGroup = binding.sourcesGroup

        if (context == null) {
            dismiss()
            Exception("FilterSheetFragment context is null").sendSilentlyWithAcraWithName("FilterSheetFragment > onCreateView")
        } else {
            CoroutineScope(Dispatchers.Main).launch {
                val tags = repository.getTags()

                tags.forEach { tag ->
                    val c = Chip(context)
                    c.text = tag.tag

                    val gd = GradientDrawable()
                    val gdColor = try {
                        Color.parseColor(tag.color)
                    } catch (e: IllegalArgumentException) {
                        e.sendSilentlyWithAcraWithName("color issue " + tag.color)
                        resources.getColor(R.color.colorPrimary)
                    }
                    gd.setColor(gdColor)
                    gd.shape = GradientDrawable.RECTANGLE
                    gd.setSize(30, 30)
                    gd.cornerRadius = 30F
                    c.chipIcon = gd

                    c.setOnCloseIconClickListener {
                        (it as Chip).isCloseIconVisible = false
                        selectedChip = null
                        repository.setTagFilter(null)
                    }

                    c.setOnClickListener {
                        if (selectedChip != null) {
                            selectedChip!!.isCloseIconVisible = false
                        }
                        (it as Chip).isCloseIconVisible = true
                        selectedChip = it
                        repository.setTagFilter(tag)

                        repository.setSourceFilter(null)
                    }

                    if (repository.tagFilter.value?.equals(tag) == true) {
                        c.isCloseIconVisible = true
                        selectedChip = c
                    }

                    tagGroup.addView(c)
                }

                repository.getSources().forEach { source ->
                    val c = Chip(context)

                    Glide.with(context)
                        .load(source.getIcon(repository.baseUrl))
                        .listener(object : RequestListener<Drawable?> {
                            override fun onLoadFailed(
                                e: GlideException?,
                                model: Any?,
                                target: Target<Drawable?>?,
                                isFirstResource: Boolean
                            ): Boolean {
                                return false
                            }

                            override fun onResourceReady(
                                resource: Drawable?,
                                model: Any?,
                                target: Target<Drawable?>?,
                                dataSource: DataSource?,
                                isFirstResource: Boolean
                            ): Boolean {
                                c.chipIcon = resource
                                return false
                            }
                        }).preload()

                    c.text = source.title.getHtmlDecoded()

                    c.setOnCloseIconClickListener {
                        (it as Chip).isCloseIconVisible = false
                        selectedChip = null
                        repository.setSourceFilter(null)
                    }

                    c.setOnClickListener {
                        if (selectedChip != null) {
                            selectedChip!!.isCloseIconVisible = false
                        }
                        (it as Chip).isCloseIconVisible = true
                        selectedChip = it
                        repository.setSourceFilter(source)

                        repository.setTagFilter(null)
                    }


                    if (repository.sourceFilter.value?.equals(source) == true) {
                        c.isCloseIconVisible = true
                        selectedChip = c
                    }

                    sourceGroup.addView(c)
                }

                binding.progressBar2.visibility = GONE
                binding.filterView.visibility = VISIBLE
            }
        }

        binding.floatingActionButton2.setOnClickListener {
            (activity as HomeActivity).getElementsAccordingToTab()
            (activity as HomeActivity).fetchOnEmptyList()
            dismiss()
        }
        return binding.root
    }

    companion object {
        const val TAG = "FilterModalBottomSheet"
    }


}