package com.remax.visualnovel.widget.imagepicker.views.wrapper

import android.content.Context
import android.view.View
import android.view.animation.AnimationUtils
import androidx.core.view.isVisible
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.remax.visualnovel.R
import com.remax.visualnovel.databinding.PickerWxPreviewBottombarBinding
import com.remax.visualnovel.extension.setOnClick
import com.remax.visualnovel.extension.toast
import com.remax.visualnovel.utils.spannablex.utils.dp
import com.remax.visualnovel.widget.itemdecoration.HorizontalItemDecoration
import com.remax.visualnovel.widget.imagepicker.adapter.MultiPreviewAdapter
import com.remax.visualnovel.widget.imagepicker.bean.ImageItem
import com.remax.visualnovel.widget.imagepicker.bean.PickerItemDisableCode
import com.remax.visualnovel.widget.imagepicker.bean.selectconfig.BaseSelectConfig
import com.remax.visualnovel.widget.imagepicker.helper.recyclerviewitemhelper.SimpleItemTouchHelperCallback
import com.remax.visualnovel.widget.imagepicker.presenter.IPickerPresenter
import com.remax.visualnovel.widget.imagepicker.views.PickerUiConfig
import com.remax.visualnovel.widget.imagepicker.views.base.PreviewControllerView

import java.io.File
import java.lang.ref.WeakReference

/**
 * Created by HJW on 2022/10/21
 */
class PreviewControllerView constructor(context: Context?) : PreviewControllerView(context) {

    private var binding: PickerWxPreviewBottombarBinding? = null

    private var previewAdapter: MultiPreviewAdapter? = null
    private var presenter: IPickerPresenter? = null
    private var selectConfig: BaseSelectConfig? = null
    private var uiConfig: PickerUiConfig? = null
    private var selectedList: ArrayList<ImageItem>? = null
    private var isShowBottomBar = true
    private var isShowCompleteBtn = true

    override fun getLayoutId(): Int = R.layout.picker_wx_preview_bottombar

    override fun initView(view: View?) {
        view?.run {
            binding = PickerWxPreviewBottombarBinding.bind(this.findViewById(R.id.group))
            binding?.let {
                setOnClick(it.mTitleContainer.navBack) {
                    onBackPressed()
                }
            }
        }
    }

    override fun setStatusBar() {

    }

    override fun initData(selectConfig: BaseSelectConfig?, presenter: IPickerPresenter?, uiConfig: PickerUiConfig?, selectedList: ArrayList<ImageItem>?) {
        this.selectConfig = selectConfig
        this.presenter = presenter
        this.selectedList = selectedList
        this.uiConfig = uiConfig
        initUI()
        initPreviewList()
        binding?.run {
            bottomBar.isVisible = isShowBottomBar
            mPreviewRecyclerView.isVisible = isShowBottomBar

            mTitleContainer.rightConfirmBtn.isVisible = isShowCompleteBtn
        }
    }

    private var currentImageItem: ImageItem? = null
    private var currentPosition = 0
    private var currentIsChecked = false

    private fun initUI() {
        binding?.run {
            setOnClick(mSelectCheckBox) {
                currentIsChecked = !currentIsChecked
                checkButton.viewChecked(currentIsChecked)
                if (currentIsChecked) {
                    if (!File(currentImageItem?.path.toString()).exists()) {
                        checkButton.viewChecked(false)
                        context.toast(context.getString(R.string.file_not_found_hint))
                    } else {
                        val disableCode = PickerItemDisableCode.getItemDisableCode(
                            currentImageItem, selectConfig, selectedList,
                            selectedList?.contains(currentImageItem) == true
                        )

                        if (disableCode != PickerItemDisableCode.NORMAL) {
                            val message = PickerItemDisableCode.getMessageFormCode(context, disableCode, presenter, selectConfig)
                            if (message.isNotEmpty()) {
                                presenter?.tip(WeakReference(context).get(), message)
                            }
                            checkButton.viewChecked(false)
                            return@setOnClick
                        }
                        if (selectedList?.contains(currentImageItem) == false) {
                            currentImageItem?.let { selectedList?.add(it) }
                        }
                    }
                } else {
                    selectedList?.remove(currentImageItem)
                }
                notifyPreviewList(currentImageItem)
                mTitleContainer.rightConfirmBtn.isEnabled = !selectedList.isNullOrEmpty()
            }
        }
    }

    private fun initPreviewList() {
        binding?.run {
            mPreviewRecyclerView.layoutManager = LinearLayoutManager(context, RecyclerView.HORIZONTAL, false)
            val space = 12.dp
            mPreviewRecyclerView.addItemDecoration(HorizontalItemDecoration(space, space * 2, space * 2))
            previewAdapter = MultiPreviewAdapter(selectedList, presenter)
            mPreviewRecyclerView.adapter = previewAdapter
            val callback = SimpleItemTouchHelperCallback(previewAdapter)
            val mItemTouchHelper = ItemTouchHelper(callback)
            mItemTouchHelper.attachToRecyclerView(mPreviewRecyclerView)
        }
    }

    override fun getCompleteView(): View? {
        return binding?.mTitleContainer?.rightConfirmBtn
    }

    override fun singleTap() {
        binding?.run {
            if (mTitleContainer.navRoot.isVisible) {
                mTitleContainer.navRoot.animation = AnimationUtils.loadAnimation(context, R.anim.picker_top_out)
                mTitleContainer.navRoot.isVisible = false
                if (isShowBottomBar) {
                    bottomBar.animation = AnimationUtils.loadAnimation(context, R.anim.picker_fade_out)
                    bottomBar.isVisible = false
                    mPreviewRecyclerView.animation = AnimationUtils.loadAnimation(context, R.anim.picker_fade_out)
                    mPreviewRecyclerView.isVisible = false
                }
            } else {
                mTitleContainer.navRoot.animation = AnimationUtils.loadAnimation(context, R.anim.picker_top_in)
                mTitleContainer.navRoot.isVisible = true
                if (isShowBottomBar) {
                    bottomBar.animation = AnimationUtils.loadAnimation(context, R.anim.picker_fade_in)
                    bottomBar.isVisible = true
                    mPreviewRecyclerView.animation = AnimationUtils.loadAnimation(context, R.anim.picker_fade_in)
                    mPreviewRecyclerView.isVisible = true
                }
            }
        }
    }

    /**
     * 刷新预览编辑列表
     *
     * @param imageItem 当前预览的图片
     */
    private fun notifyPreviewList(imageItem: ImageItem?) {
        previewAdapter?.setPreviewImageItem(imageItem)
        if (selectedList?.contains(imageItem) == true) {
            binding?.mPreviewRecyclerView?.smoothScrollToPosition(selectedList?.indexOf(imageItem) ?: 0)
        }
    }

    override fun onPageSelected(position: Int, imageItem: ImageItem?, totalPreviewCount: Int) {
        binding?.run {
            currentPosition = position
            currentImageItem = imageItem
            mTitleContainer.tvTitle.text = String.format("%d/%d", position + 1, totalPreviewCount)
            currentIsChecked = selectedList?.contains(imageItem) == true
            checkButton.viewChecked(currentIsChecked)
            notifyPreviewList(imageItem)

            if ((selectConfig?.maxCount ?: 0) <= 1 && selectConfig?.isSinglePickAutoComplete == true) {
                mTitleContainer.rightConfirmBtn.isVisible = false
            } else {
                mTitleContainer.rightConfirmBtn.isVisible = true
                mTitleContainer.rightConfirmBtn.isEnabled = !selectedList.isNullOrEmpty()
            }
        }
    }
}