package com.bearya.kids.chapter

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.observe
import androidx.navigation.findNavController
import androidx.navigation.fragment.navArgs
import androidx.recyclerview.widget.GridLayoutManager
import com.bearya.data.entity.Chapter
import com.bearya.kids.R
import com.bearya.kids.databinding.FragmentChapterBinding
import library.ext.setData

class ChapterFragment : Fragment() {

    private val gradeLevelPrimary = 1 // 小班
    private val gradeLevelMiddle = 2 // 中班
    private val gradeLevelLarge = 3 // 大班

    private lateinit var bindView: FragmentChapterBinding
    private val viewModel: ChapterViewModel by viewModels()
    private val args: ChapterFragmentArgs by navArgs()

    private val chapterAdapter: ChapterAdapter by lazy {
        ChapterAdapter().apply {
            onItemClickListener = { view: View, item: Chapter?, _: Int ->
                view.findNavController().navigate(
                    ChapterFragmentDirections.actionChapterFragmentToSectionFragment(
                        item?.id
                            ?: 1, item?.name
                    )
                )
            }
        }
    }

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

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

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

        bindView.gradeName.text = when (args.grade) {
            gradeLevelPrimary -> "小班"
            gradeLevelMiddle -> "中班"
            gradeLevelLarge -> "大班"
            else -> "幼儿园"
        }

        bindView.back.setOnClickListener { v -> v.findNavController().navigateUp() }
        bindView.chapter.layoutManager =
            GridLayoutManager(context, 2, GridLayoutManager.HORIZONTAL, false)
        bindView.chapter.adapter = chapterAdapter

        viewModel.chapters.observe(viewLifecycleOwner) {
            chapterAdapter.submitList(it)
        }

    }

}