package kr.co.vividnext.sodalive.explorer.profile.creator_community.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 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.common.SharedPreferenceManager
import kr.co.vividnext.sodalive.databinding.ActivityCreatorCommunityModifyBinding
import kr.co.vividnext.sodalive.extensions.dpToPx
import kr.co.vividnext.sodalive.extensions.loadUrl
import org.koin.android.ext.android.inject

class CreatorCommunityModifyActivity : BaseActivity<ActivityCreatorCommunityModifyBinding>(
    ActivityCreatorCommunityModifyBinding::inflate
) {

    private val viewModel: CreatorCommunityModifyViewModel 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.ivContent.background = null
                binding.ivContent.load(fileUri) {
                    crossfade(true)
                    placeholder(R.drawable.ic_place_holder)
                    transformations(RoundedCornersTransformation(8f.dpToPx()))
                }
                viewModel.imageUri = 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)
        checkPermissions()

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

        bindData()

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

        viewModel.postId = postId
        viewModel.getCommunityPostDetail(
            onFailure = {
                Toast.makeText(applicationContext, "잘못된 요청입니다.", Toast.LENGTH_LONG).show()
                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) }
        }

        if (SharedPreferenceManager.isAuth) {
            binding.llSetAdult.visibility = View.VISIBLE
        } else {
            binding.llSetAdult.visibility = View.GONE
        }

        binding.llCommentNo.setOnClickListener { viewModel.setAvailableComment(false) }
        binding.llCommentYes.setOnClickListener { viewModel.setAvailableComment(true) }
        binding.tvCancel.setOnClickListener { finish() }
        binding.tvUpload.setOnClickListener {
            viewModel.modifyCommunityPost {
                setResult(RESULT_OK)
                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.etContent.textChanges().skip(1)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe {
                    binding.tvNumberOfCharacters.text = "${it.length}자"
                    viewModel.content = 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.imageUrlLiveData.observe(this) {
            if (!it.isNullOrBlank()) {
                binding.ivContent.background = null
                binding.ivContent.loadUrl(it) {
                    crossfade(true)
                    placeholder(R.drawable.ic_place_holder)
                    transformations(RoundedCornersTransformation(8f.dpToPx()))
                }
            }
        }

        viewModel.contentLiveData.observe(this) {
            binding.etContent.setText(it)
        }

        viewModel.isAvailableCommentLiveData.observe(this) {
            if (it) {
                binding.ivCommentYes.visibility = View.VISIBLE
                binding.tvCommentYes.setTextColor(
                    ContextCompat.getColor(
                        applicationContext,
                        R.color.white
                    )
                )
                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_80d8ff
                    )
                )
                binding.llCommentNo.setBackgroundResource(
                    R.drawable.bg_round_corner_6_7_13181b
                )
            } else {
                binding.ivCommentNo.visibility = View.VISIBLE
                binding.tvCommentNo.setTextColor(
                    ContextCompat.getColor(
                        applicationContext,
                        R.color.white
                    )
                )
                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_80d8ff
                    )
                )
                binding.llCommentYes
                    .setBackgroundResource(R.drawable.bg_round_corner_6_7_13181b)
            }
        }

        if (SharedPreferenceManager.isAuth) {
            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_80d8ff
                        )
                    )

                    binding.ivAge19.visibility = View.VISIBLE
                    binding.llAge19.setBackgroundResource(R.drawable.bg_round_corner_6_7_3bb9f1)
                    binding.tvAge19.setTextColor(
                        ContextCompat.getColor(
                            applicationContext,
                            R.color.white
                        )
                    )
                } 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_80d8ff
                        )
                    )

                    binding.ivAgeAll.visibility = View.VISIBLE
                    binding.llAgeAll.setBackgroundResource(R.drawable.bg_round_corner_6_7_3bb9f1)
                    binding.tvAgeAll.setTextColor(
                        ContextCompat.getColor(
                            applicationContext,
                            R.color.white
                        )
                    )
                }
            }
        }
    }
}
