package com.bearya.kids.section

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.observe
import androidx.navigation.findNavController
import androidx.navigation.fragment.navArgs
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.viewpager2.widget.ViewPager2
import com.bearya.data.entity.Section
import com.bearya.kids.databinding.FragmentSectionBinding
import kotlinx.coroutines.*
import library.ext.setData

class SectionFragment : Fragment() {

    private lateinit var bindView: FragmentSectionBinding
    private val viewModel: SectionViewModel by viewModels()
    private val args: SectionFragmentArgs by navArgs()

    private val sectionQuestionAdapter: SectionQuestionAdapter by lazy { SectionQuestionAdapter(args.chapterName) }
    private val previewAdapter: SectionPreviewAdapter by lazy { SectionPreviewAdapter(args.chapterName) }

    private val pageChangeCallback by lazy {
        object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                previewAdapter.setSelectedIndex(position)
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        viewModel.chapterId.setData(args.chapterId)
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        bindView = FragmentSectionBinding.inflate(inflater, container, false)
        bindView.lifecycleOwner = viewLifecycleOwner
        return bindView.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {

        bindView.playPager.adapter = sectionQuestionAdapter

        bindView.playPager.registerOnPageChangeCallback(pageChangeCallback)

        sectionQuestionAdapter.onItemClickListener = { _: View, _: Section?, _: Int ->
            cancelHideSectionPreview()

            val visibility = bindView.playList.visibility.takeIf { it == View.VISIBLE }
                    ?.let { View.GONE } ?: View.VISIBLE
            bindView.playList.visibility = visibility
            bindView.back.visibility = visibility
            bindView.analysis.visibility = visibility

            hideSectionPreview()

        }

        bindView.playList.layoutManager =
                LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)
        bindView.playList.adapter = previewAdapter

        previewAdapter.onItemClickListener = { _: View, _: Section?, position: Int ->
            bindView.playPager.currentItem = position
        }

        viewModel.sections.observe(viewLifecycleOwner) {
            sectionQuestionAdapter.submitList(it)
            previewAdapter.submitList(it)
        }

        bindView.back.setOnClickListener { v -> v.findNavController().navigateUp() }

        bindView.analysis.setOnClickListener {
            val itemData = sectionQuestionAdapter.getItemData(bindView.playPager.currentItem)

            if (itemData?.hasAnalysis == true) {
                val action = SectionFragmentDirections.actionSectionFragmentToAnalysisFragment(itemData.id ?: 1 , args.chapterName)
                it.findNavController().navigate(action)
            } else {
                Toast.makeText(context, "暂无该答案", Toast.LENGTH_LONG).show()
            }
        }

    }

    override fun onResume() {
        super.onResume()
        hideSectionPreview()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        bindView.playPager.unregisterOnPageChangeCallback(pageChangeCallback)
    }

    private var launchDelayHide: Job? = null

    private fun hideSectionPreview() {
        launchDelayHide = lifecycleScope.launch {
            delay(3000)
            withContext(Dispatchers.Main) {
                bindView.playList.visibility.takeIf { it == View.VISIBLE }?.also {
                    bindView.playList.visibility = View.GONE
                    bindView.back.visibility = View.GONE
                    bindView.analysis.visibility = View.GONE
                }
            }
        }
    }

    private fun cancelHideSectionPreview() = launchDelayHide?.cancel()

}