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

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.activityViewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.all.pdfreader.pro.app.R
import com.all.pdfreader.pro.app.databinding.DialogBookmarksBinding
import com.all.pdfreader.pro.app.model.RenameType
import com.all.pdfreader.pro.app.room.entity.BookmarkEntity
import com.all.pdfreader.pro.app.room.entity.PdfDocumentEntity
import com.all.pdfreader.pro.app.ui.adapter.BookmarkAdapter
import com.all.pdfreader.pro.app.util.ToastUtils
import com.all.pdfreader.pro.app.viewmodel.PdfViewModel
import com.google.android.material.bottomsheet.BottomSheetDialogFragment

class BookmarksDialogFragment(
    private val pdfDocument: PdfDocumentEntity, private val onJumpPage: (Int) -> Unit
) : BottomSheetDialogFragment() {

    private lateinit var binding: DialogBookmarksBinding
    private val viewModel: PdfViewModel by activityViewModels()//为PdfViewActivity的PdfViewModel
    private lateinit var bookmarks: List<BookmarkEntity>
    private lateinit var adapter: BookmarkAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        /**
         * 让 BottomSheetDialogFragment 覆盖底部导航栏
         * 原理：
         * 1.自定义样式，并继承自 @style/Theme.Design.BottomSheetDialog
         * 2.xml布局设置fitsSystemWindows
         */
        setStyle(STYLE_NORMAL, R.style.CustomBottomSheetDialogTheme)
    }

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

    override fun onStart() {
        super.onStart()
        dialog?.window?.findViewById<View>(com.google.android.material.R.id.design_bottom_sheet)
            ?.setBackgroundResource(R.drawable.dr_rc_top_12_bg_white)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        if (pdfDocument.filePath.isEmpty()) {
            showToast(getString(R.string.file_not))
            dismiss()
        }
        viewModel.pdfBookmark.value?.let {
            bookmarks = it
            initView()
            setupOnClick()
        } ?: run {
            showToast(getString(R.string.bookmark_loading))
            dismiss()
        }
    }

    private fun initView() {
        adapter = BookmarkAdapter(list = mutableListOf(), onItemClick = { bookmark ->
            onJumpPage(bookmark.pageNumber)
            dismiss()
        }, onEditClick = { bookmark, position ->
            RenameDialogFragment(RenameType.BOOKMARK, bookmark, onOkClick = { updatedBookmark ->
                bookmarks = bookmarks.map {//更新外部数据
                    if (it.id == updatedBookmark.id) updatedBookmark else it
                }
                adapter.updateItemChanged(updatedBookmark)//更新adapter数据
            }).show(
                parentFragmentManager, "BookmarksDialogFragment"
            )
        }, onDeleteClick = { bookmark, position ->
            adapter.removeItem(position)
            bookmarks = bookmarks.filter { it.id != bookmark.id }
            viewModel.deleteBookMark(bookmark)
        })
        binding.bookmarksPageRv.layoutManager = LinearLayoutManager(requireContext())
        binding.bookmarksPageRv.adapter = adapter
        updateUi()
        updateAdapter()
    }

    private fun updateUi(){
        if (bookmarks.isEmpty()) {
            binding.noBookmarksPageLayout.visibility = View.VISIBLE//显示没有书签的提示布局
            binding.bookmarksDisplayLayout.visibility = View.GONE//隐藏显示内容的布局
            binding.addBtn.visibility = View.GONE//隐藏顶部的add按钮（因为布局noBookmarksPageLayout里面也会有一个add按钮）
        } else {
            binding.noBookmarksPageLayout.visibility = View.GONE
            binding.bookmarksDisplayLayout.visibility = View.VISIBLE
            binding.addBtn.visibility = View.VISIBLE
            // 检查当前页是否已存在书签
            val alreadyBookmarked = bookmarks.any { it.pageNumber == pdfDocument.lastReadPage }
            binding.addBtn.isEnabled = !alreadyBookmarked
            if (alreadyBookmarked) {
                binding.addTv.text = getString(R.string.added)
                binding.addTv.setTextColor(requireActivity().getColor(R.color.white))
                binding.addBtn.setBackgroundResource(R.drawable.dr_btn_not_clickable_bg)
                binding.addIv.setImageResource(R.drawable.bookmark_icon_white)
            } else {
                binding.addTv.text = getString(R.string.add)
                binding.addTv.setTextColor(requireActivity().getColor(R.color.white))
                binding.addBtn.setBackgroundResource(R.drawable.dr_click_btn_bg)
                binding.addIv.setImageResource(R.drawable.add_icon_white)
            }
        }
    }

    private fun setupOnClick() {
        binding.addBookmarkBtn.setOnClickListener {
            dialogAddBookMarks()
        }
        binding.addBtn.setOnClickListener {
            dialogAddBookMarks()
        }
        binding.deleteALLPageBtn.setOnClickListener {
            PromptDialogFragment(
                getString(R.string.delete_bookmarks_title),
                getString(R.string.delete_bookmarks_desc),
                onOkClick = {
                    viewModel.deleteAllBookmark(pdfDocument.filePath)
                    adapter.removeAllItems()
                    bookmarks = emptyList()
                    updateUi()
                }).show(parentFragmentManager, "deleteAllBookmark")
        }
    }

    private fun dialogAddBookMarks() {
        val bookmark = BookmarkEntity(
            filePath = pdfDocument.filePath,
            pageNumber = pdfDocument.lastReadPage,
            label = getString(R.string.page) + " ${pdfDocument.lastReadPage + 1}"
        )
        viewModel.addBookMark(bookmark)
        dismiss()
    }

    private fun updateAdapter() {
        if (bookmarks.isNotEmpty()) {
            val sortedBookmarks = bookmarks.sortedByDescending { it.createTime }
            adapter.updateData(sortedBookmarks)
        }
    }

    private fun showToast(message: String) {
        ToastUtils.show(requireActivity(), message)
    }
}