package kr.co.vividnext.sodalive.mypage

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Rect
import android.net.Uri
import android.os.Bundle
import android.view.View
import android.webkit.URLUtil
import android.widget.LinearLayout
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import coil.load
import coil.transform.CircleCropTransformation
import com.google.gson.Gson
import kr.co.vividnext.sodalive.R
import kr.co.vividnext.sodalive.audio_content.detail.AudioContentDetailActivity
import kr.co.vividnext.sodalive.audio_content.order.AudioContentOrderListActivity
import kr.co.vividnext.sodalive.audio_content.order.AudioContentOrderListAdapter
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.common.SharedPreferenceManager
import kr.co.vividnext.sodalive.databinding.FragmentMyBinding
import kr.co.vividnext.sodalive.explorer.profile.UserProfileActivity
import kr.co.vividnext.sodalive.extensions.dpToPx
import kr.co.vividnext.sodalive.extensions.moneyFormat
import kr.co.vividnext.sodalive.following.FollowingCreatorActivity
import kr.co.vividnext.sodalive.live.reservation_status.LiveReservationStatusActivity
import kr.co.vividnext.sodalive.mypage.alarm.AlarmListActivity
import kr.co.vividnext.sodalive.mypage.auth.Auth
import kr.co.vividnext.sodalive.mypage.auth.AuthVerifyRequest
import kr.co.vividnext.sodalive.mypage.auth.BootpayResponse
import kr.co.vividnext.sodalive.mypage.block.BlockMemberActivity
import kr.co.vividnext.sodalive.mypage.can.charge.CanChargeActivity
import kr.co.vividnext.sodalive.mypage.can.coupon.CanCouponActivity
import kr.co.vividnext.sodalive.mypage.can.status.CanStatusActivity
import kr.co.vividnext.sodalive.mypage.profile.ProfileUpdateActivity
import kr.co.vividnext.sodalive.mypage.service_center.ServiceCenterActivity
import kr.co.vividnext.sodalive.settings.SettingsActivity
import kr.co.vividnext.sodalive.settings.notification.MemberRole
import org.koin.android.ext.android.inject

class MyPageFragment : BaseFragment<FragmentMyBinding>(FragmentMyBinding::inflate) {

    private val viewModel: MyPageViewModel by inject()

    private lateinit var loadingDialog: LoadingDialog
    private lateinit var orderListAdapter: AudioContentOrderListAdapter

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        loadingDialog = LoadingDialog(requireActivity(), layoutInflater)

        setupView()
        bindData()
    }

    override fun onStart() {
        super.onStart()
        viewModel.getUserInfo()
    }

    private fun setupView() {
        orderListAdapter = AudioContentOrderListAdapter {
            startActivity(
                Intent(requireContext(), AudioContentDetailActivity::class.java)
                    .apply { putExtra(Constants.EXTRA_AUDIO_CONTENT_ID, it) }
            )
        }

        binding.rvOrderList.layoutManager = LinearLayoutManager(
            requireContext(),
            LinearLayoutManager.VERTICAL,
            false
        )

        binding.rvOrderList.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)) {
                    orderListAdapter.itemCount - 1 -> {
                        outRect.bottom = 0
                    }

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

        binding.rvOrderList.adapter = orderListAdapter

        binding.ivSettings.setOnClickListener {
            startActivity(
                Intent(
                    requireActivity(),
                    SettingsActivity::class.java
                )
            )
        }

        binding.ivEdit.setOnClickListener {
            startActivity(
                Intent(
                    requireActivity(),
                    ProfileUpdateActivity::class.java
                )
            )
        }

        if (SharedPreferenceManager.userId == 17958L) {
            binding.llCan.visibility = View.GONE
        } else {
            binding.llCan.visibility = View.VISIBLE
            binding.llTotalCan.setOnClickListener {
                startActivity(
                    Intent(
                        requireActivity(),
                        CanStatusActivity::class.java
                    )
                )
            }

            binding.tvChargeCan.setOnClickListener {
                startActivity(
                    Intent(
                        requireActivity(),
                        CanChargeActivity::class.java
                    )
                )
            }
        }

        binding.rlCoupon.setOnClickListener {
            startActivity(
                Intent(
                    requireActivity(),
                    CanCouponActivity::class.java
                )
            )
        }

        binding.rlAlarm.setOnClickListener {
            startActivity(
                Intent(
                    requireActivity(),
                    AlarmListActivity::class.java
                )
            )
        }

        binding.llReservationLive.setOnClickListener {
            startActivity(
                Intent(
                    requireActivity(),
                    LiveReservationStatusActivity::class.java
                )
            )
        }

        binding.rlServiceCenter.setOnClickListener {
            startActivity(
                Intent(
                    requireActivity(),
                    ServiceCenterActivity::class.java
                )
            )
        }

        binding.tvAuth.setOnClickListener {
            Auth.auth(requireActivity(), requireContext()) {
                val bootpayResponse = Gson().fromJson(it, BootpayResponse::class.java)
                val request = AuthVerifyRequest(receiptId = bootpayResponse.data.receiptId)
                requireActivity().runOnUiThread {
                    viewModel.authVerify(request)
                }
            }
        }

        if (SharedPreferenceManager.role == MemberRole.CREATOR.name) {
            binding.tvMyChannel.visibility = View.VISIBLE
            binding.tvMyChannel.setOnClickListener {
                startActivity(
                    Intent(
                        requireContext(),
                        UserProfileActivity::class.java
                    ).apply {
                        putExtra(
                            Constants.EXTRA_USER_ID,
                            SharedPreferenceManager.userId
                        )
                    }
                )
            }
        } else {
            binding.tvMyChannel.visibility = View.GONE
        }

        binding.tvFollowingList.setOnClickListener {
            startActivity(Intent(requireContext(), FollowingCreatorActivity::class.java))
        }

        binding.tvBlockMemberList.setOnClickListener {
            startActivity(Intent(requireContext(), BlockMemberActivity::class.java))
        }

        val ivHowToUseLp = binding.ivHowToUse.layoutParams as LinearLayout.LayoutParams
        ivHowToUseLp.width = screenWidth
        ivHowToUseLp.height = (200 * screenWidth) / 1080
        binding.ivHowToUse.layoutParams = ivHowToUseLp
        binding.ivHowToUse.setOnClickListener {
            val url = "https://blog.naver.com/sodalive_official"
            if (URLUtil.isValidUrl(url)) {
                startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)))
            }
        }
    }

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

        viewModel.isLoading.observe(viewLifecycleOwner) {
            if (it) {
                loadingDialog.show(screenWidth)
            } else {
                loadingDialog.dismiss()
            }
        }

        viewModel.myPageLiveData.observe(viewLifecycleOwner) {
            if (it.isAuth) {
                binding.tvAuth.visibility = View.GONE
                binding.rlCoupon.visibility = View.VISIBLE
            } else {
                binding.tvAuth.visibility = View.VISIBLE
                binding.rlCoupon.visibility = View.GONE
            }

            binding.ivProfile.load(it.profileUrl) {
                crossfade(true)
                placeholder(R.drawable.ic_place_holder)
                transformations(CircleCropTransformation())
            }
            binding.tvNickname.text = it.nickname

            if (it.websiteUrl.isNullOrBlank() || !URLUtil.isValidUrl(it.websiteUrl)) {
                binding.ivWebsite.visibility = View.GONE
            } else {
                binding.ivWebsite.visibility = View.VISIBLE
                binding.ivWebsite.setOnClickListener { _ ->
                    startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(it.websiteUrl)))
                }
            }

            if (it.blogUrl.isNullOrBlank() || !URLUtil.isValidUrl(it.blogUrl)) {
                binding.ivBlog.visibility = View.GONE
            } else {
                binding.ivBlog.visibility = View.VISIBLE
                binding.ivBlog.setOnClickListener { _ ->
                    startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(it.blogUrl)))
                }
            }

            if (it.instagramUrl.isNullOrBlank() || !URLUtil.isValidUrl(it.instagramUrl)) {
                binding.ivInstagram.visibility = View.GONE
            } else {
                binding.ivInstagram.visibility = View.VISIBLE
                binding.ivInstagram.setOnClickListener { _ ->
                    startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(it.instagramUrl)))
                }
            }

            if (it.youtubeUrl.isNullOrBlank() || !URLUtil.isValidUrl(it.youtubeUrl)) {
                binding.ivYoutube.visibility = View.GONE
            } else {
                binding.ivYoutube.visibility = View.VISIBLE
                binding.ivYoutube.setOnClickListener { _ ->
                    startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(it.youtubeUrl)))
                }
            }

            binding.tvTotalCan.text = (it.chargeCan + it.rewardCan).moneyFormat()
            binding.tvReservationLive.text = "${it.liveReservationCount}"

            if (it.orderList.totalCount > 0) {
                binding.llOrderList.visibility = View.VISIBLE
                orderListAdapter.items.addAll(it.orderList.items)
                orderListAdapter.notifyDataSetChanged()

                binding.tvAllOrderList.setOnClickListener {
                    startActivity(
                        Intent(
                            requireContext(),
                            AudioContentOrderListActivity::class.java
                        )
                    )
                }
            } else {
                binding.llOrderList.visibility = View.GONE
            }
        }
    }
}
