package cz.muni.sutralog.ui.list

import android.app.AlertDialog
import android.app.Dialog
import android.content.DialogInterface
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.*
import android.widget.LinearLayout
import androidx.appcompat.widget.SearchView
import androidx.appcompat.widget.Toolbar
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import cz.muni.sutralog.R
import cz.muni.sutralog.data.CategoryPresentableListItem
import cz.muni.sutralog.databinding.CategoriesListBinding
import cz.muni.sutralog.databinding.RocksListBinding
import cz.muni.sutralog.repository.CategoryRepository

class CategoryListFragment : Fragment() {
    private lateinit var binding: CategoriesListBinding
    private lateinit var adapter: CategoryAdapter
    //all categories from db
    private lateinit var allCategories : List<CategoryPresentableListItem>
    //filtered categories
    private lateinit var categories : List<CategoryPresentableListItem>
    private lateinit var toolbar: Toolbar
    private var searchKey: String = ""

    private val categoryRepository: CategoryRepository by lazy {
        CategoryRepository(requireContext())
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        if (!this::binding.isInitialized) {
            binding = CategoriesListBinding.inflate(LayoutInflater.from(context), container, false)
        }
        return binding.root
    }

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

        allCategories = categoryRepository.getAllCategories()
        categories = allCategories

        binding.addCategoryButton.setOnClickListener {
            findNavController()
                .navigate(
                    CategoryListFragmentDirections
                        .actionCategoryListFragmentToCategoryEditFragment(
                            CategoryPresentableListItem(
                                color = -12953037,
                                name = ""
                            ), true
                        )
                )
        }

        setupToolbar()
        initAdapter()
        performFiltering()
        submitList()
    }

    private fun performFiltering() {
        categories = allCategories.filter {
                category -> category.name.contains(searchKey)
        }
        submitList()
    }

    private fun submitList() {
        adapter.submitList(categories)
    }

    private fun setupToolbar(){
        if(this::toolbar.isInitialized){
            return
        }
        toolbar = binding.toolbar

        toolbar.setOnMenuItemClickListener {
            when (it.itemId) {
                R.id.show_all_dao -> findNavController()
                    .navigate(
                        CategoryListFragmentDirections
                            .actionCategoryListToRocksList(0, true)
                    )
            }
            true
        }

        val searchItem = toolbar.menu.findItem(R.id.search)
        val searchView = searchItem.actionView as SearchView

        searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
            override fun onQueryTextSubmit(query: String?): Boolean {
                return false
            }

            override fun onQueryTextChange(newText: String?): Boolean {
                if(newText.toString().isNotEmpty() && newText.toString().trim().isEmpty()){
                    searchView.setQuery("", false)
                    return false
                }
                searchKey = newText.toString()
                performFiltering()
                return false
            }
        })
    }

    private fun initAdapter(){
        if(this::adapter.isInitialized){
            return
        }

        adapter = CategoryAdapter(
            onItemClick = {
                findNavController()
                    .navigate(
                        CategoryListFragmentDirections
                            .actionCategoryListToRocksList(it.id, false)
                    )
            },
            onItemLongClick = {
                showCategoryDialog(it)
            }
        )

        binding.recyclerView.adapter = adapter
    }

    private fun showCategoryDialog(item: CategoryPresentableListItem): Boolean {
        val dialog = Dialog(requireContext())
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
        dialog.setContentView(R.layout.bs_rock_options)

        val editLayout = dialog.findViewById<LinearLayout>(R.id.edit_layout)
        val removeLayout = dialog.findViewById<LinearLayout>(R.id.remove_layout)

        editLayout.setOnClickListener {
            findNavController()
                .navigate(
                    CategoryListFragmentDirections
                        .actionCategoryListFragmentToCategoryEditFragment(item)
                )
            dialog.hide()
        }

        removeLayout.setOnClickListener {
            dialog.hide()
            removeCategory(item)
        }

        dialog.show()
        dialog.window?.setLayout(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT
        )
        dialog.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        dialog.window?.attributes?.windowAnimations = R.style.DialogAnimation
        dialog.window?.setGravity(Gravity.BOTTOM)
        return true
    }

    private fun removeCategory(item: CategoryPresentableListItem) {
        AlertDialog.Builder(requireContext())
            .setMessage("Opravdu smazat?")
            .setCancelable(false)
            .setNegativeButton("Zrušit") { dialogInterface: DialogInterface, i: Int ->
                dialogInterface.dismiss()
            }
            .setPositiveButton("Smazat") { dialogInterface: DialogInterface, i: Int ->
                AlertDialog.Builder(requireContext())
                    .setMessage("Budou smazany vsechny kameny, presto chcete smazat?")
                    .setCancelable(false)
                    .setNegativeButton("Zrušit") { dialogInterface: DialogInterface, i: Int ->
                        dialogInterface.dismiss()
                    }
                    .setPositiveButton("Smazat") { dialogInterface: DialogInterface, i: Int ->
                        deleteCategory(item)
                    }
                    .show()
            }
            .show()
    }

    private fun deleteCategory(item: CategoryPresentableListItem) {
        categoryRepository.deleteCategory(item)
        var index = categories.indexOf(item)
        allCategories = allCategories.minus(item)
        categories = categories.minus(item)
        adapter.removeItem(index)
    }
}


