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.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.all.pdfreader.pro.app.R
import com.all.pdfreader.pro.app.databinding.FragmentHomeBinding
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 com.all.pdfreader.pro.app.util.PdfScanner
import kotlinx.coroutines.launch

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

    companion object {
        const val FRAG_TAG = "HomeFrag"
    }

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

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

    fun setupMultiSelect() {
        onItemLongClickListener?.onItemLongClicked(FragmentType.HOME)
        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 {
            lifecycleScope.launch {
                val pdfScanner = PdfScanner(requireContext(), getRepository())
                pdfScanner.scanAndLoadPdfFiles(true) { b ->
                    binding.swipeRefreshLayout.isRefreshing = false
                }
            }
        }

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

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

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

    private fun onSortTypeChanged(sortType: String) {
        appStore.documentSortType = sortType
        updateSortUi(sortType)
        // 排序类型改变时重新加载数据
        observeDocuments()
    }

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

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

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

    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)
            }
        }
    }
}