package kr.co.vividnext.sodalive.mypage.can.status.charge

import android.annotation.SuppressLint
import android.graphics.Rect
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import kr.co.vividnext.sodalive.base.BaseFragment
import kr.co.vividnext.sodalive.databinding.FragmentCanStatusBinding
import kr.co.vividnext.sodalive.extensions.dpToPx
import kr.co.vividnext.sodalive.mypage.can.status.CanStatusViewModel

class CanChargeStatusFragment(
    private val viewModel: CanStatusViewModel
) : BaseFragment<FragmentCanStatusBinding>(
    FragmentCanStatusBinding::inflate
) {

    private lateinit var adapter: CanChargeStatusAdapter

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

        setupView()
        bindData()
        viewModel.getCanChargeStatus()
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun setupView() {
        val recyclerView = binding.rvCanStatus
        adapter = CanChargeStatusAdapter()

        recyclerView.layoutManager = LinearLayoutManager(
            requireContext(),
            LinearLayoutManager.VERTICAL,
            false
        )

        recyclerView.addItemDecoration(object : RecyclerView.ItemDecoration() {
            override fun getItemOffsets(
                outRect: Rect,
                view: View,
                parent: RecyclerView,
                state: RecyclerView.State
            ) {
                super.getItemOffsets(outRect, view, parent, state)

                when (parent.getChildAdapterPosition(view)) {
                    0 -> {
                        outRect.top = 13.3f.dpToPx().toInt()
                        outRect.bottom = 6.7f.dpToPx().toInt()
                    }

                    adapter.itemCount - 1 -> {
                        outRect.top = 6.7f.dpToPx().toInt()
                        outRect.bottom = 13.3f.dpToPx().toInt()
                    }

                    else -> {
                        outRect.top = 6.7f.dpToPx().toInt()
                        outRect.bottom = 6.7f.dpToPx().toInt()
                    }
                }
            }
        })

        recyclerView.adapter = adapter
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun bindData() {
        viewModel.canChargeStatusLiveData.observe(viewLifecycleOwner) {
            adapter.items.addAll(it)
            adapter.notifyDataSetChanged()
        }

        viewModel.toastLiveData.observe(viewLifecycleOwner) {
            it?.let { Toast.makeText(requireContext(), it, Toast.LENGTH_LONG).show() }
        }
    }
}
