package com.bearya.kids.section

import android.os.Bundle
import android.view.KeyEvent
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 com.orhanobut.logger.Logger
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 pagerAdapter: SectionPagerAdapter by lazy { SectionPagerAdapter(args.chapterName) }
    private val previewAdapter: SectionPreviewAdapter by lazy { SectionPreviewAdapter(args.chapterName) }

    private val pageChangeCallback by lazy {
        object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                viewModel.playIndex.setData(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 = pagerAdapter
        bindView.playPager.registerOnPageChangeCallback(pageChangeCallback)
        pagerAdapter.onItemClickListener = { _: View, _: Section?, _: Int ->
            onItemEvents()
        }
        bindView.playPager.setOnKeyListener { _, keyCode, event ->
            Logger.d("有了点击事件了keycode = $keyCode 和 event = ${event.action}")
            if (KeyEvent.ACTION_UP == event.action) {
                when (keyCode) {
                    KeyEvent.KEYCODE_MENU -> onItemEvents()
                    KeyEvent.KEYCODE_BACK -> view.findNavController().navigateUp()
                    KeyEvent.KEYCODE_DPAD_LEFT -> {
                        if (viewModel.playIndex.value ?: 0 > 0) {
                            viewModel.playIndex.setData(viewModel.playIndex.value?.minus(1))
                        }
                    }
                    KeyEvent.KEYCODE_DPAD_RIGHT -> {
                        if (viewModel.playIndex.value ?: 0 < viewModel.sectionDirFileSize - 1) {
                            viewModel.playIndex.setData(viewModel.playIndex.value?.plus(1))
                        }
                    }
                }
            }
            true
        }
        bindView.playPager.setOnFocusChangeListener { v, hasFocus ->
            if (!hasFocus) {
                v.requestFocus()
            }
        }

        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) {
            pagerAdapter.submitList(it)
            previewAdapter.submitList(it)
            viewModel.sectionDirFileSize = it.size
        }

        viewModel.playIndex.observe(viewLifecycleOwner) {
            previewAdapter.setSelectedIndex(it)
        }

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

        bindView.analysis.setOnClickListener {
            val itemData = pagerAdapter.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 fun onItemEvents(){
        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()
    }

    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()

}