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.databinding.FragmentRecentlyBinding
import com.all.pdfreader.pro.app.model.FragmentType
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 kotlinx.coroutines.launch

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

    companion object {
        const val FRAG_TAG = "RecentlyFrag"
    }

    private lateinit var binding: FragmentRecentlyBinding
    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 = FragmentRecentlyBinding.inflate(layoutInflater)
        return binding.root
    }

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

    fun setupMultiSelect() {
        onItemLongClickListener?.onItemLongClicked(FragmentType.RECENTLY)
        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
            }
        }
    }

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

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

    private fun observeDocuments(onComplete: () -> Unit = {}) {
        lifecycleScope.launch {
            PdfRepository.getInstance().getRecentlyOpenedDocuments().collect { list ->
                if (list.isNotEmpty()) {
                    adapter.updateData(list)
                    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
        }
    }
}