package kr.co.vividnext.sodalive.audio_content.modify

import android.Manifest
import android.annotation.SuppressLint
import android.os.Build
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.ContextCompat
import androidx.core.view.setPadding
import coil.load
import coil.transform.RoundedCornersTransformation
import com.github.dhaval2404.imagepicker.ImagePicker
import com.gun0912.tedpermission.PermissionListener
import com.gun0912.tedpermission.normal.TedPermission
import com.jakewharton.rxbinding4.widget.textChanges
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.schedulers.Schedulers
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.RealPathUtil
import kr.co.vividnext.sodalive.databinding.ActivityAudioContentModifyBinding
import kr.co.vividnext.sodalive.extensions.dpToPx
import org.koin.android.ext.android.inject

class AudioContentModifyActivity : BaseActivity<ActivityAudioContentModifyBinding>(
    ActivityAudioContentModifyBinding::inflate
) {

    private val viewModel: AudioContentModifyViewModel by inject()

    private lateinit var loadingDialog: LoadingDialog

    private val imageResult = registerForActivityResult(
        ActivityResultContracts.StartActivityForResult()
    ) { result ->
        val resultCode = result.resultCode
        val data = result.data

        if (resultCode == RESULT_OK) {
            val fileUri = data?.data

            if (fileUri != null) {
                binding.ivCover.setPadding(0)
                binding.ivCover.background = null
                binding.ivCover.load(fileUri) {
                    crossfade(true)
                    placeholder(R.drawable.bg_placeholder)
                    transformations(RoundedCornersTransformation(13.3f.dpToPx()))
                }
                viewModel.coverImageUri = fileUri
            } else {
                Toast.makeText(
                    this,
                    "잘못된 파일입니다.\n다시 선택해 주세요.",
                    Toast.LENGTH_SHORT
                ).show()
            }
        } else if (resultCode == ImagePicker.RESULT_ERROR) {
            Toast.makeText(this, ImagePicker.getError(data), Toast.LENGTH_SHORT).show()
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val audioContentId = intent.getLongExtra(Constants.EXTRA_AUDIO_CONTENT_ID, 0)
        if (audioContentId <= 0) {
            Toast.makeText(applicationContext, "잘못된 요청입니다.", Toast.LENGTH_LONG).show()
            finish()
        }

        checkPermissions()

        viewModel.getRealPathFromURI = {
            RealPathUtil.getRealPath(applicationContext, it)
        }

        bindData()
        viewModel.getAudioContentDetail(audioContentId = audioContentId) { finish() }
    }

    override fun setupView() {
        loadingDialog = LoadingDialog(this, layoutInflater)
        binding.toolbar.tvBack.text = "콘텐츠 수정"
        binding.toolbar.tvBack.setOnClickListener { finish() }

        binding.ivPhotoPicker.setOnClickListener {
            ImagePicker.with(this)
                .crop()
                .galleryOnly()
                .galleryMimeTypes( // Exclude gif images
                    mimeTypes = arrayOf(
                        "image/png",
                        "image/jpg",
                        "image/jpeg"
                    )
                )
                .createIntent { imageResult.launch(it) }
        }

        binding.llCommentNo.setOnClickListener { viewModel.setAvailableComment(false) }
        binding.llCommentYes.setOnClickListener { viewModel.setAvailableComment(true) }

        binding.tvCancel.setOnClickListener { finish() }
        binding.tvModify.setOnClickListener {
            viewModel.modifyAudioContent { finish() }
        }
    }

    private fun checkPermissions() {
        val permissions = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            listOf(Manifest.permission.READ_MEDIA_AUDIO)
        } else {
            listOf(Manifest.permission.READ_EXTERNAL_STORAGE)
        }

        TedPermission.create()
            .setPermissionListener(object : PermissionListener {
                override fun onPermissionGranted() {
                }

                override fun onPermissionDenied(deniedPermissions: MutableList<String>?) {
                    finish()
                }
            })
            .setDeniedMessage(R.string.read_storage_permission_denied_message)
            .setPermissions(*permissions.toTypedArray())
            .check()
    }

    @SuppressLint("SetTextI18n")
    private fun bindData() {
        compositeDisposable.add(
            binding.etTitle.textChanges().skip(1)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe {
                    viewModel.title = it.toString()
                }
        )

        compositeDisposable.add(
            binding.etDetail.textChanges().skip(1)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe {
                    binding.tvNumberOfCharacters.text = "${it.length}자"
                    viewModel.detail = it.toString()
                }
        )

        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.isAvailableCommentLiveData.observe(this) {
            if (it) {
                binding.ivCommentYes.visibility = View.VISIBLE
                binding.tvCommentYes.setTextColor(
                    ContextCompat.getColor(
                        applicationContext,
                        R.color.color_eeeeee
                    )
                )
                binding.llCommentYes.setBackgroundResource(R.drawable.bg_round_corner_6_7_3bb9f1)

                binding.ivCommentNo.visibility = View.GONE
                binding.tvCommentNo.setTextColor(
                    ContextCompat.getColor(
                        applicationContext,
                        R.color.color_3bb9f1
                    )
                )
                binding.llCommentNo.setBackgroundResource(
                    R.drawable.bg_round_corner_6_7_13181b_3bb9f1
                )
            } else {
                binding.ivCommentNo.visibility = View.VISIBLE
                binding.tvCommentNo.setTextColor(
                    ContextCompat.getColor(
                        applicationContext,
                        R.color.color_eeeeee
                    )
                )
                binding.llCommentNo.setBackgroundResource(R.drawable.bg_round_corner_6_7_3bb9f1)

                binding.ivCommentYes.visibility = View.GONE
                binding.tvCommentYes.setTextColor(
                    ContextCompat.getColor(
                        applicationContext,
                        R.color.color_3bb9f1
                    )
                )
                binding.llCommentYes
                    .setBackgroundResource(R.drawable.bg_round_corner_6_7_13181b_3bb9f1)
            }
        }

        viewModel.isAdultShowUiLiveData.observe(this) {
            if (it) {
                binding.llSetAdult.visibility = View.VISIBLE

                binding.llAgeAll.setOnClickListener {
                    viewModel.setAdult(false)
                }

                binding.llAge19.setOnClickListener {
                    viewModel.setAdult(true)
                }

                viewModel.isAdultLiveData.observe(this) {
                    if (it) {
                        binding.ivAgeAll.visibility = View.GONE
                        binding.llAgeAll.setBackgroundResource(
                            R.drawable.bg_round_corner_6_7_13181b
                        )
                        binding.tvAgeAll.setTextColor(
                            ContextCompat.getColor(
                                applicationContext,
                                R.color.color_3bb9f1
                            )
                        )

                        binding.ivAge19.visibility = View.VISIBLE
                        binding.llAge19.setBackgroundResource(R.drawable.bg_round_corner_6_7_3bb9f1)
                        binding.tvAge19.setTextColor(
                            ContextCompat.getColor(
                                applicationContext,
                                R.color.color_eeeeee
                            )
                        )
                    } else {
                        binding.ivAge19.visibility = View.GONE
                        binding.llAge19.setBackgroundResource(R.drawable.bg_round_corner_6_7_13181b)
                        binding.tvAge19.setTextColor(
                            ContextCompat.getColor(
                                applicationContext,
                                R.color.color_3bb9f1
                            )
                        )

                        binding.ivAgeAll.visibility = View.VISIBLE
                        binding.llAgeAll.setBackgroundResource(
                            R.drawable.bg_round_corner_6_7_3bb9f1
                        )
                        binding.tvAgeAll.setTextColor(
                            ContextCompat.getColor(
                                applicationContext,
                                R.color.color_eeeeee
                            )
                        )
                    }
                }
            } else {
                binding.llSetAdult.visibility = View.GONE
            }
        }

        viewModel.coverImageLiveData.observe(this) {
            binding.ivCover.setPadding(0)
            binding.ivCover.background = null
            binding.ivCover.load(it) {
                crossfade(true)
                placeholder(R.drawable.bg_placeholder)
                transformations(RoundedCornersTransformation(13.3f.dpToPx()))
            }
        }

        viewModel.titleLiveData.observe(this) {
            binding.etTitle.setText(it)
        }

        viewModel.detailLiveData.observe(this) {
            binding.etDetail.setText(it)
        }
    }
}
