package com.all.pdfreader.pro.app.ui.fragment

import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.recyclerview.widget.LinearLayoutManager
import com.all.pdfreader.pro.app.R
import com.all.pdfreader.pro.app.databinding.FragmentFavoriteBinding
import com.all.pdfreader.pro.app.model.FragmentType
import com.all.pdfreader.pro.app.model.SortConfig
import com.all.pdfreader.pro.app.model.SortField
import com.all.pdfreader.pro.app.room.entity.PdfDocumentEntity
import com.all.pdfreader.pro.app.room.repository.PdfRepository
import com.all.pdfreader.pro.app.ui.act.MainActivity
import com.all.pdfreader.pro.app.ui.act.PdfViewActivity
import com.all.pdfreader.pro.app.ui.adapter.PdfAdapter
import com.all.pdfreader.pro.app.ui.dialog.ListMoreDialogFragment
import com.all.pdfreader.pro.app.ui.dialog.SortDialogFragment
import com.all.pdfreader.pro.app.util.AppUtils.setOnSingleClickListener
import kotlinx.coroutines.launch

class FavoriteFrag : BaseFrag(){
    override val TAG: String = "FavoriteFrag"

    companion object {
        const val FRAG_TAG = "FavoriteFrag"
    }

    private lateinit var binding: FragmentFavoriteBinding
    lateinit var adapter: PdfAdapter

    private var onItemLongClickListener: OnItemLongClickListener? = null

    interface OnItemLongClickListener {
        fun onItemLongClicked(type: FragmentType)
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View {
        binding = FragmentFavoriteBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView()
        observeDocuments()
        updateSortUi(appStore.favoriteSortType)
    }

    fun setupMultiSelect() {
        onItemLongClickListener?.onItemLongClicked(FragmentType.FAVORITE)
        updateSwipeRefreshState()
        (requireActivity() as? MainActivity)?.updateSelectNumber(adapter.getSelectedItems().size)
        adapter.setIsMultiSelectMode(true)
    }

    private fun initView() {
        adapter = PdfAdapter(pdfList = mutableListOf(), onItemClick = { pdf ->
            val intent = PdfViewActivity.createIntent(requireContext(), pdf.filePath)
            startActivity(intent)
        }, onMoreClick = { pdf ->
            ListMoreDialogFragment(pdf.filePath).show(parentFragmentManager, FRAG_TAG)
        }, onLongClick = { pdf ->
            setupMultiSelect()
        }, onSelectModelItemClick = { number ->
            (requireActivity() as? MainActivity)?.updateSelectNumber(number)
        })

        binding.recyclerView.layoutManager = LinearLayoutManager(requireContext())
        binding.recyclerView.adapter = adapter

        // 下拉刷新示例
        binding.swipeRefreshLayout.setOnRefreshListener {
            observeDocuments {
                binding.swipeRefreshLayout.isRefreshing = false
            }
        }

        binding.sortingBtn.setOnSingleClickListener {
            SortDialogFragment(FavoriteFrag(), onOkClick = { it ->
                updateSortUi(it)
                onSortFavoriteTypeChanged(it)
            }).show(parentFragmentManager, TAG)
        }
    }

    fun updateSwipeRefreshState() {
        binding.swipeRefreshLayout.isEnabled = !adapter.getIsMultiSelectMode()
    }

    fun exitMultiSelectMode() {
        adapter.exitMultiSelectMode()
        updateSwipeRefreshState()
    }

    private fun observeDocuments(onComplete: () -> Unit = {}) {
        lifecycleScope.launch {
            PdfRepository.getInstance().getFavoriteDocuments().collect { list ->
                val sortedList = sortDocuments(list)
                if (sortedList.isNotEmpty()) {
                    adapter.updateData(sortedList)
                    onComplete()
                    binding.noFilesLayout.visibility = View.GONE
                } else {
                    binding.noFilesLayout.visibility = View.VISIBLE
                }
            }
        }
    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
        if (context is OnItemLongClickListener) {
            onItemLongClickListener = context
        }
    }

    private fun onSortFavoriteTypeChanged(sortType: String) {
        appStore.favoriteSortType = sortType
        updateSortUi(sortType)
        observeDocuments()
    }

    private fun sortDocuments(documents: List<PdfDocumentEntity>): List<PdfDocumentEntity> {
        val sortConfig = SortConfig.fromPreferenceString(appStore.favoriteSortType)
        return sortConfig.applySortFavorite(documents)
    }

    private fun updateSortUi(type: String) {
        val config = SortConfig.fromPreferenceString(type)
        when (config.field) {
            SortField.NAME -> {
                binding.sortingTv.text = getString(R.string.sort_by_name)
            }

            SortField.DATE -> {
                binding.sortingTv.text = getString(R.string.sort_by_last_modified)
            }

            SortField.SIZE -> {
                binding.sortingTv.text = getString(R.string.sort_by_size)
            }
        }
    }
}