package com.all.pdfreader.pdf.reader.ui.dialog

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

class BookmarksDialogFragment() : BottomSheetDialogFragment() {

    companion object {
        private const val ARG_FILE_PATH = "arg_file_path"
        private const val ARG_LAST_READ_PAGE = "arg_last_read_page"
        fun newInstance(pdfDocument: PdfDocumentEntity): BookmarksDialogFragment {
            val fragment = BookmarksDialogFragment()
            val args = Bundle()
            args.putString(ARG_FILE_PATH, pdfDocument.filePath)
            args.putInt(ARG_LAST_READ_PAGE, pdfDocument.lastReadPage)
            fragment.arguments = args
            return fragment
        }
    }

    private val filePath: String
        get() = arguments?.getString(ARG_FILE_PATH) ?: ""

    private val lastReadPage: Int
        get() = arguments?.getInt(ARG_LAST_READ_PAGE) ?: 0


    var onJumpPage: ((Int) -> Unit)? = null

    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)
        if (savedInstanceState != null) {
            dismissAllowingStateLoss()
            return
        }
        /**
         * 让 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? {
        if (savedInstanceState != null) return null
        binding = DialogBookmarksBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun show(manager: FragmentManager, tag: String?) {
        if (!manager.isStateSaved) {
            super.show(manager, tag)
        }
    }

    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)
        AnalyticsUtils.logEvent(AnalyticsUtils.Event.BOOKMARK_TK_SHOW)
        if (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?.invoke(bookmark.pageNumber)
            dismiss()
        }, onEditClick = { bookmark, position ->
            val renameDialogFragment = RenameDialogFragment.newInstance(
                RenameType.BOOKMARK, bookmark
            )
            renameDialogFragment.onOkClick = { updatedBookmark ->
                bookmarks = bookmarks.map {//更新外部数据
                    if (it.id == updatedBookmark.id) updatedBookmark else it
                }
                adapter.updateItemChanged(updatedBookmark)//更新adapter数据
            }
            renameDialogFragment.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 == 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 {
            val promptDialogFragment = PromptDialogFragment.newInstance(
                title =  getString(R.string.delete_bookmarks_title),
                desc = getString(R.string.delete_bookmarks_desc)
            )
            promptDialogFragment.onOkClick = {
                viewModel.deleteAllBookmark(filePath)
                adapter.removeAllItems()
                bookmarks = emptyList()
                updateUi()
            }
            promptDialogFragment.show(parentFragmentManager, "deleteAllBookmark")
        }
    }

    private fun dialogAddBookMarks() {
        val bookmark = BookmarkEntity(
            filePath = filePath,
            pageNumber = lastReadPage,
            label = getString(R.string.page) + " ${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)
    }
}