package kr.co.vividnext.sodalive.message.text

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.graphics.Rect
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import kr.co.vividnext.sodalive.R
import kr.co.vividnext.sodalive.base.BaseFragment
import kr.co.vividnext.sodalive.common.Constants
import kr.co.vividnext.sodalive.common.LoadingDialog
import kr.co.vividnext.sodalive.databinding.FragmentTextMessageBinding
import kr.co.vividnext.sodalive.extensions.dpToPx
import kr.co.vividnext.sodalive.message.MessageBox
import org.koin.android.ext.android.inject

class TextMessageFragment : BaseFragment<FragmentTextMessageBinding>(
    FragmentTextMessageBinding::inflate
) {
    private val viewModel: TextMessageViewModel by inject()

    private lateinit var activityResultLauncher: ActivityResultLauncher<Intent>
    private lateinit var adapter: TextMessageAdapter

    private lateinit var loadingDialog: LoadingDialog

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        activityResultLauncher = registerForActivityResult(
            ActivityResultContracts.StartActivityForResult()
        ) {
            if (it.resultCode == Activity.RESULT_OK) {
                viewModel.page = 1
                viewModel.getMessages()
            }
        }
    }

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

        setupView()
        bindData()

        viewModel.getMessages()
    }

    private fun setupView() {
        loadingDialog = LoadingDialog(requireActivity(), layoutInflater)

        binding.tvSent.setOnClickListener {
            viewModel.selectMessageBox(MessageBox.SENT)
        }

        binding.tvReceive.setOnClickListener {
            viewModel.selectMessageBox(MessageBox.RECEIVE)
        }

        binding.tvKeep.setOnClickListener {
            viewModel.selectMessageBox(MessageBox.KEEP)
        }

        binding.ivWrite.setOnClickListener {
            val intent = Intent(requireActivity(), TextMessageWriteActivity::class.java)
            activityResultLauncher.launch(intent)
        }

        val recyclerView = binding.rvMessage
        adapter = TextMessageAdapter {
            val intent = Intent(requireActivity(), TextMessageDetailActivity::class.java)
            intent.putExtra(Constants.EXTRA_TEXT_MESSAGE, it)
            intent.putExtra(
                Constants.EXTRA_MESSAGE_BOX,
                viewModel.messageBoxLiveData.value!!.name
            )
            activityResultLauncher.launch(intent)
        }

        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)

                outRect.left = 13.3f.dpToPx().toInt()
                outRect.right = 13.3f.dpToPx().toInt()
                outRect.top = 13.3f.dpToPx().toInt()
                outRect.bottom = 13.3f.dpToPx().toInt()
            }
        })

        recyclerView.adapter = adapter

        recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)

                val lastVisibleItemPosition = (recyclerView.layoutManager as LinearLayoutManager?)!!
                    .findLastCompletelyVisibleItemPosition()
                val itemTotalCount = recyclerView.adapter!!.itemCount - 1

                // 스크롤이 끝에 도달했는지 확인
                if (!recyclerView.canScrollVertically(1) &&
                    lastVisibleItemPosition == itemTotalCount
                ) {
                    viewModel.getMessages(viewModel.messageBoxLiveData.value!!)
                }
            }
        })
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun bindData() {
        viewModel.toastLiveData.observe(viewLifecycleOwner) {
            it?.let { Toast.makeText(requireActivity(), it, Toast.LENGTH_LONG).show() }
        }

        viewModel.isLoading.observe(viewLifecycleOwner) {
            if (it) {
                loadingDialog.show(screenWidth, "문자 메시지를 불러오고 있습니다.")
            } else {
                loadingDialog.dismiss()
            }
        }

        viewModel.getMessagesLiveData.observe(viewLifecycleOwner) {
            if (viewModel.page - 1 == 1) {
                adapter.items.clear()
            }

            if (adapter.items.size == 0 && it.isEmpty()) {
                binding.rvMessage.visibility = View.GONE
                binding.llNoItems.visibility = View.VISIBLE
            } else {
                binding.rvMessage.visibility = View.VISIBLE
                binding.llNoItems.visibility = View.GONE
                adapter.items.addAll(it)
                adapter.notifyDataSetChanged()
            }
        }

        viewModel.messageBoxLiveData.observe(viewLifecycleOwner) {
            binding.tvSent.setBackgroundResource(R.drawable.bg_round_corner_16_7_transparent_777777)
            binding.tvSent.setTextColor(
                ContextCompat.getColor(
                    requireContext(),
                    R.color.color_777777
                )
            )

            binding.tvReceive.setBackgroundResource(
                R.drawable.bg_round_corner_16_7_transparent_777777
            )
            binding.tvReceive.setTextColor(
                ContextCompat.getColor(
                    requireContext(),
                    R.color.color_777777
                )
            )

            binding.tvKeep.setBackgroundResource(
                R.drawable.bg_round_corner_16_7_transparent_777777
            )
            binding.tvKeep.setTextColor(
                ContextCompat.getColor(
                    requireContext(),
                    R.color.color_777777
                )
            )

            when (it) {
                MessageBox.SENT -> {
                    binding.tvSent.setBackgroundResource(
                        R.drawable.bg_round_corner_16_7_transparent_3bb9f1
                    )
                    binding.tvSent.setTextColor(
                        ContextCompat.getColor(
                            requireContext(),
                            R.color.color_3bb9f1
                        )
                    )
                }

                MessageBox.RECEIVE -> {
                    binding.tvReceive.setBackgroundResource(
                        R.drawable.bg_round_corner_16_7_transparent_3bb9f1
                    )
                    binding.tvReceive.setTextColor(
                        ContextCompat.getColor(
                            requireContext(),
                            R.color.color_3bb9f1
                        )
                    )
                }

                MessageBox.KEEP -> {
                    binding.tvKeep.setBackgroundResource(
                        R.drawable.bg_round_corner_16_7_transparent_3bb9f1
                    )
                    binding.tvKeep.setTextColor(
                        ContextCompat.getColor(
                            requireContext(),
                            R.color.color_3bb9f1
                        )
                    )
                }

                else -> {
                }
            }
        }
    }
}
