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

import android.animation.ValueAnimator
import android.graphics.PorterDuff
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.AccelerateDecelerateInterpolator
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.fragment.app.activityViewModels
import com.all.pdfreader.pro.app.R
import com.all.pdfreader.pro.app.databinding.DialogViewModelBinding
import com.all.pdfreader.pro.app.room.entity.PdfDocumentEntity
import com.all.pdfreader.pro.app.sp.AppStore
import com.all.pdfreader.pro.app.ui.view.CustomSwitchButton
import com.all.pdfreader.pro.app.ui.view.CustomSwitchButton.OnCheckedChangeListener
import com.all.pdfreader.pro.app.util.ToastUtils
import com.all.pdfreader.pro.app.viewmodel.PdfViewModel
import com.google.android.material.bottomsheet.BottomSheetDialogFragment

class ViewModelDialogFragment() : BottomSheetDialogFragment() {

    private lateinit var binding: DialogViewModelBinding
    private val viewModel: PdfViewModel by activityViewModels()//为PdfViewActivity的PdfViewModel
    private lateinit var pdfDocument: PdfDocumentEntity
    private var isFirstSetSelected = true// 第一次直接设置位置，不做指示器的切换动画
    private val appstore by lazy { AppStore(requireActivity()) }

    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 = DialogViewModelBinding.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)
        viewModel.pdfDocument.value?.let {
            pdfDocument = it
            initUi()
            setupOnClick()
        } ?: run {
            showToast(getString(R.string.file_not))
            dismiss()
        }
    }

    private fun initUi() {
        // 初始化指示器宽度
        binding.indicator.post {
            val indicatorWidth = binding.btnHorizontal.width
            binding.indicator.layoutParams.width = indicatorWidth
            binding.indicator.requestLayout()
            setSelectedMode(appstore.isVertical)
        }
        binding.switchPageByPage.setChecked(appstore.isPageFling)
        binding.switchColorInversion.setChecked(appstore.isColorInversion)
    }

    private fun setupOnClick() {
        binding.btnHorizontal.setOnClickListener {
            setSelectedMode(isVertical = false)
            AppStore(requireActivity()).isVertical = false
            viewModel.setSwipeVertical(false)
        }
        binding.btnVertical.setOnClickListener {
            setSelectedMode(isVertical = true)
            AppStore(requireActivity()).isVertical = true
            viewModel.setSwipeVertical(true)
        }
        binding.switchPageByPage.setOnCheckedChangeListener(object : OnCheckedChangeListener {
            override fun onCheckedChanged(view: CustomSwitchButton?, isChecked: Boolean) {
                view?.setChecked(isChecked)
                appstore.isPageFling = isChecked
                viewModel.setPageFling(appstore.isPageFling)
            }
        })
        binding.switchColorInversion.setOnCheckedChangeListener(object : OnCheckedChangeListener {
            override fun onCheckedChanged(
                view: CustomSwitchButton?,
                isChecked: Boolean
            ) {
                view?.setChecked(isChecked)
                appstore.isColorInversion = isChecked
                viewModel.setColorInversion(appstore.isColorInversion)
            }
        })
    }

    private fun setSelectedMode(isVertical: Boolean) {
        binding.apply {
            val targetX = if (isVertical) btnVertical.x else btnHorizontal.x

            if (isFirstSetSelected) {
                indicator.translationX = targetX
                isFirstSetSelected = false
            } else {
                indicator.animate().translationX(targetX).setDuration(250)
                    .setInterpolator(AccelerateDecelerateInterpolator()).start()
            }

            // 横向
            animateIconAndTextColor(
                horizontalTv,
                horizontalIv,
                if (isVertical) requireContext().getColor(R.color.white)
                else requireContext().getColor(R.color.text_color_lv1),
                if (isVertical) requireContext().getColor(R.color.text_color_lv1)
                else requireContext().getColor(R.color.white)
            )
            // 垂直
            animateIconAndTextColor(
                verticalTv,
                verticalIv,
                if (isVertical) requireContext().getColor(R.color.text_color_lv1)
                else requireContext().getColor(R.color.white),
                if (isVertical) requireContext().getColor(R.color.white)
                else requireContext().getColor(R.color.text_color_lv1)
            )
        }
    }


    /**
     * 改变img与text的颜色值，动画渐变同步indicator的时间
     */
    private fun animateIconAndTextColor(
        textView: TextView, imageView: ImageView, fromColor: Int, toColor: Int
    ) {
        ValueAnimator.ofArgb(fromColor, toColor).apply {
            duration = 250
            addUpdateListener { animator ->
                val animatedColor = animator.animatedValue as Int
                textView.setTextColor(animatedColor)
                imageView.setColorFilter(animatedColor, PorterDuff.Mode.SRC_IN)
            }
            start()
        }
    }


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