package kr.co.vividnext.sodalive.audio_content.series.detail

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.core.content.res.ResourcesCompat
import coil.load
import coil.size.Scale
import coil.transform.BlurTransformation
import coil.transform.CircleCropTransformation
import coil.transform.RoundedCornersTransformation
import com.google.android.material.chip.Chip
import com.google.android.material.shape.ShapeAppearanceModel
import com.google.android.material.tabs.TabLayout
import kr.co.vividnext.sodalive.R
import kr.co.vividnext.sodalive.base.BaseActivity
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.ActivitySeriesDetailBinding
import kr.co.vividnext.sodalive.explorer.profile.CreatorFollowNotifyFragment
import kr.co.vividnext.sodalive.extensions.dpToPx
import org.koin.android.ext.android.inject

class SeriesDetailActivity : BaseActivity<ActivitySeriesDetailBinding>(
    ActivitySeriesDetailBinding::inflate
) {
    private val viewModel: SeriesDetailViewModel by inject()

    private lateinit var loadingDialog: LoadingDialog

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val seriesId = intent.getLongExtra(Constants.EXTRA_SERIES_ID, 0)
        if (seriesId <= 0) {
            Toast.makeText(applicationContext, "잘못된 요청입니다.", Toast.LENGTH_LONG).show()
            finish()
        }

        bindData()

        viewModel.seriesId = seriesId
        viewModel.getSeriesDetail()
    }

    override fun setupView() {
        loadingDialog = LoadingDialog(this, layoutInflater)
        binding.ivBack.setOnClickListener { finish() }

        setupTab()
    }

    private fun setupTab() {
        val tabs = binding.tabs
        tabs.addTab(tabs.newTab().setText("홈").setTag("home"))
        tabs.addTab(tabs.newTab().setText("작품소개").setTag("introduction"))

        tabs.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab) {
                val tag = tab.tag as String
                changeFragment(tag)
            }

            override fun onTabUnselected(tab: TabLayout.Tab) {
            }

            override fun onTabReselected(tab: TabLayout.Tab) {
            }

        })
    }

    private fun changeFragment(tag: String) {
        val fragmentManager = supportFragmentManager
        val fragmentTransaction = fragmentManager.beginTransaction()

        val fragment = when (tag) {
            "introduction" -> SeriesDetailIntroductionFragment()
            else -> SeriesDetailHomeFragment()
        }

        val bundle = Bundle()
        bundle.putParcelable(Constants.EXTRA_SERIES, viewModel.seriesDetailResponse)
        fragment.arguments = bundle

        fragmentTransaction.replace(R.id.container, fragment, tag)
        fragmentTransaction.setPrimaryNavigationFragment(fragment)
        fragmentTransaction.setReorderingAllowed(true)
        fragmentTransaction.commitNow()
    }

    private fun bindData() {
        viewModel.toastLiveData.observe(this) {
            it?.let { Toast.makeText(applicationContext, it, Toast.LENGTH_LONG).show() }
        }

        viewModel.isLoading.observe(this) {
            if (it) {
                loadingDialog.show(screenWidth, "")
            } else {
                loadingDialog.dismiss()
            }
        }

        viewModel.seriesDetailLiveData.observe(this) {
            setSeriesBg(it.coverImage)
            setSeriesInfo(it)
            setSeriesCreator(it.creator)
            setSeriesKeywordChipList(it.keywordList)

            changeFragment("home")
        }
    }

    private fun setSeriesKeywordChipList(keywordList: List<String>) {
        binding.chipGroup.isSingleLine = true
        binding.chipGroup.isHorizontalScrollBarEnabled = false

        for (keyword in keywordList) {
            val chip = Chip(this)
            chip.text = keyword
            chip.isClickable = false
            chip.isCheckable = false
            chip.textSize = 12f
            chip.chipStrokeWidth = 0f
            chip.setChipBackgroundColorResource(R.color.color_222222)

            val shapeAppearanceModel = ShapeAppearanceModel.Builder()
                .setAllCornerSizes(26.7f.dpToPx())
                .build()
            chip.shapeAppearanceModel = shapeAppearanceModel

            chip.setPadding(0, 0, 0, 0)
            chip.setTextColor(ContextCompat.getColor(applicationContext, R.color.color_d2d2d2))
            chip.typeface = ResourcesCompat.getFont(applicationContext, R.font.gmarket_sans_medium)
            binding.chipGroup.addView(chip)
        }
    }

    @SuppressLint("SetTextI18n")
    private fun setSeriesInfo(seriesDetail: GetSeriesDetailResponse) {
        binding.ivCover.load(seriesDetail.coverImage) {
            crossfade(true)
            placeholder(R.drawable.bg_placeholder)
            transformations(RoundedCornersTransformation(5f.dpToPx()))
        }

        binding.tvTitle.text = seriesDetail.title
        binding.tvGenre.text = seriesDetail.genre
        binding.tvPublishedDaysOfWeek.text = "${seriesDetail.publishedDaysOfWeek} 연재"

        if (seriesDetail.isAdult) {
            binding.tvAge19.visibility = View.VISIBLE
            binding.tvAgeAll.visibility = View.GONE
        } else {
            binding.tvAge19.visibility = View.GONE
            binding.tvAgeAll.visibility = View.VISIBLE
        }
    }

    private fun setSeriesCreator(creator: GetSeriesDetailResponse.GetSeriesDetailCreator) {
        binding.tvNickname.text = creator.nickname
        binding.ivProfile.load(creator.profileImage) {
            crossfade(true)
            placeholder(R.drawable.bg_placeholder)
            transformations(CircleCropTransformation())
        }

        if (SharedPreferenceManager.userId != creator.creatorId) {
            binding.ivFollow.visibility = View.VISIBLE

            if (creator.isFollow) {
                binding.ivFollow.setImageResource(
                    if (creator.isNotify) {
                        R.drawable.btn_following_big
                    } else {
                        R.drawable.btn_following_no_alarm_big
                    }
                )
            } else {
                binding.ivFollow.setImageResource(R.drawable.btn_follow_big)
            }
        } else {
            binding.ivFollow.visibility = View.GONE
        }

        binding.ivFollow.setOnClickListener {
            if (creator.isFollow) {
                val notifyFragment = CreatorFollowNotifyFragment(
                    onClickNotifyAll = {
                        viewModel.follow(
                            creatorId = creator.creatorId,
                            follow = true,
                            notify = true
                        ) {
                            creator.isFollow = true
                            creator.isNotify = true
                            binding.ivFollow.setImageResource(R.drawable.btn_following_big)
                        }
                    },
                    onClickNotifyNone = {
                        viewModel.follow(
                            creatorId = creator.creatorId,
                            follow = true,
                            notify = false
                        ) {
                            creator.isFollow = true
                            creator.isNotify = false
                            binding.ivFollow.setImageResource(R.drawable.btn_following_no_alarm_big)
                        }
                    },
                    onClickUnFollow = {
                        viewModel.follow(
                            creatorId = creator.creatorId,
                            follow = false,
                            notify = false
                        ) {
                            creator.isFollow = false
                            creator.isNotify = false
                            binding.ivFollow.setImageResource(R.drawable.btn_follow_big)
                        }
                    }
                )

                if (notifyFragment.isAdded) return@setOnClickListener
                notifyFragment.show(supportFragmentManager, notifyFragment.tag)
            } else {
                viewModel.follow(creatorId = creator.creatorId) {
                    creator.isFollow = true
                    creator.isNotify = true
                    binding.ivFollow.setImageResource(R.drawable.btn_following_big)
                }
            }
        }
    }

    private fun setSeriesBg(coverImage: String) {
        binding.ivBg.load(coverImage) {
            transformations(
                BlurTransformation(
                    this@SeriesDetailActivity,
                    25f,
                    2.5f
                )
            )
            scale(Scale.FILL)
        }
    }
}
