package com.remax.visualnovel.ui.main.actor


import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.dylanc.loadingstateview.BgColorType
import com.remax.visualnovel.R
import com.remax.visualnovel.app.base.BaseBindingFragment
import com.remax.visualnovel.app.widget.setMyEmptyView
import com.remax.visualnovel.configs.NovelApplication
import com.remax.visualnovel.databinding.FragmentMainActorBinding
import com.remax.visualnovel.entity.request.ParamActorList
import com.remax.visualnovel.entity.request.ParamActorTag
import com.remax.visualnovel.entity.response.ActorBean
import com.remax.visualnovel.extension.launchAndCollect2
import com.remax.visualnovel.utils.Routers
import com.remax.visualnovel.utils.StatusBarUtil3
import com.remax.visualnovel.widget.custom.ActorTag
import dagger.hilt.android.AndroidEntryPoint
import kotlin.getValue
import kotlin.math.max


@AndroidEntryPoint
@Route(path = Routers.ROUTE_FRAG_ACTORLIST)
class ActorListFragment : BaseBindingFragment<FragmentMainActorBinding>() {

    private lateinit var mActorAdapter: ActorsAdapter
    private val mActorsModel by viewModels<ActorsViewModel>()
    private var mLoadedPageIndex = 0
    private val mRequestParam by lazy { ParamActorList() }
    private val mRequestTagsParam by lazy { ParamActorTag() }


    override fun onCreated(bundle: Bundle?) {
        setUI()
    }

    override fun backgroundColorType(): BgColorType {
        return BgColorType.TRANSPARENT
    }

    override fun lazyInit() {
        getActorTags()
        getActorList(true, showLoading = false)
    }

    private fun setUI() {
        with(binding.root) {
            setPadding(
                paddingLeft,
                paddingTop + StatusBarUtil3.getStatusBarHeight(context),
                paddingRight,
                paddingBottom
            )
        }

        initTagLayout()
        initRecyclerView()
    }



    private fun initRecyclerView() {
        with(binding) {
            val layoutManager = LayoutManagerHelper.createAdaptiveStaggeredGridLayoutManager()
            mActorsRv.layoutManager = layoutManager
            mActorsRv.addItemDecoration(GridSpacingItemDecoration(16))
            mActorsRv.setHasFixedSize(true)
            mActorsRv.itemAnimator = DefaultItemAnimator()

            mActorAdapter = ActorsAdapter()
            mActorsRv.adapter = mActorAdapter
            val characterList = createSampleData()
            with(mActorAdapter) {
                setList(characterList)
                loadMoreModule.setOnLoadMoreListener {
                    getActorList(false, showLoading = false)
                }
            }

            with(refreshLayout) {
                onRefresh {
                    getActorList(true, showLoading = false)
                }
            }
        }
    }

    private fun initTagLayout() {
        with(binding) {
            /*val tags = listOf(
                ActorTag(1, "Youth"),
                ActorTag(2, "Lolita"),
                ActorTag(3, "Lolita2"),
                ActorTag(4, "Overbearing CEO ABCDEFG Overbearing CEO ABCDEFG Overbearing CEO ABCDEFG"),
                ActorTag(5, "ggggggggggg CEO ABCDEFG Overbearing CEO ABCDEFG Overbearing CEO ABCDEFG"),
            )

            tagFlowLayout.setTagDataList(tags)
            */
            tagFlowLayout.setOnTagClickListener { tag ->
                Toast.makeText(context, "Clicked: ${tag.name}", Toast.LENGTH_SHORT).show()
            }

            tagFlowLayout.setOnExpandStateChangeListener { isExpanded ->
                Log.d("TagFlowLayout", "Expand state: $isExpanded")
            }
        }
    }


    private fun getActorList(isRefresh: Boolean, showLoading: Boolean) {
        if (isRefresh) {
            mLoadedPageIndex = 0
        }
        mRequestParam.index = mLoadedPageIndex + 1

        launchAndCollect2({
            mActorsModel.getActorList(mRequestParam)
        }, showLoading = showLoading) {
            onSuccess = {
                val data = it ?: emptyList()
                with(mActorAdapter) {
                    if (isRefresh) {
                        setList(data)
                        setMyEmptyView(R.string.no_character_yet, topMargin = 60)
                    } else {
                        addData(data)
                        loadMoreModule.loadMoreComplete()
                    }
                    if (data.size < mRequestParam.limit) {
                        loadMoreModule.loadMoreEnd()
                    }
                }
                if (data.isNotEmpty()) {
                    mLoadedPageIndex++
                }
            }

            onComplete = {
                if (isRefresh) {
                    binding.refreshLayout.finishRefresh()
                }
            }
        }

    }


    private fun getActorTags() {
        mRequestTagsParam.limit = Int.MAX_VALUE

        launchAndCollect2({
            mActorsModel.getActorTags(mRequestTagsParam)
        }, showLoading = false) {
            onSuccess = {
                val data = it ?: emptyList()
                binding.tagFlowLayout.setTagDataList(data)
            }
        }

    }


    private fun createSampleData(): List<ActorBean> {
        return listOf()
    }




    companion object {
        fun newInstance(): ActorListFragment {
            return ARouter.getInstance().build(Routers.ROUTE_FRAG_ACTORLIST)
                .navigation() as ActorListFragment
        }
    }

    object LayoutManagerHelper {
        fun createAdaptiveStaggeredGridLayoutManager(): StaggeredGridLayoutManager {
            val displayMetrics = NovelApplication.appContext().resources.displayMetrics
            val screenWidthPx = displayMetrics.widthPixels
            val screenWidthDp = screenWidthPx / displayMetrics.density
            // 计算列数
            val columnCount = when {
                screenWidthDp >= 600 -> {
                    max(3, (screenWidthDp / 200).toInt())
                }
                else -> {
                    2
                }
            }
            return StaggeredGridLayoutManager(columnCount, StaggeredGridLayoutManager.VERTICAL)
        }
    }

}