package kr.co.vividnext.sodalive.audio_content.upload

import android.Manifest
import android.annotation.SuppressLint
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.OpenableColumns
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.CircleCropTransformation
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.audio_content.upload.theme.AudioContentThemeFragment
import kr.co.vividnext.sodalive.base.BaseActivity
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.ActivityAudioContentUploadBinding
import kr.co.vividnext.sodalive.dialog.LiveDialog
import kr.co.vividnext.sodalive.extensions.dpToPx
import org.koin.android.ext.android.inject
import java.io.File

class AudioContentUploadActivity : BaseActivity<ActivityAudioContentUploadBinding>(
    ActivityAudioContentUploadBinding::inflate
) {

    private val viewModel: AudioContentUploadViewModel by inject()

    private lateinit var loadingDialog: LoadingDialog

    private val themeFragment: AudioContentThemeFragment by lazy {
        AudioContentThemeFragment(
            getSelectedTheme = { viewModel.theme },
            onItemClick = {
                binding.ivTheme.load(it.image) {
                    crossfade(true)
                    placeholder(R.drawable.bg_placeholder)
                    transformations(CircleCropTransformation())

                    binding.ivTheme.visibility = View.VISIBLE
                }
                binding.tvTheme.text = it.theme
                viewModel.theme = it
            }
        )
    }

    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.background = null
                binding.ivCover.load(fileUri) {
                    crossfade(true)
                    placeholder(R.drawable.ic_place_holder)
                    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()
        }
    }

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

        if (resultCode == RESULT_OK) {
            val fileUri = data?.data
            if (fileUri != null) {
                binding.tvSelectContent.text = getFileName(fileUri)
                viewModel.contentUri = fileUri
            } else {
                Toast.makeText(
                    this,
                    "잘못된 파일입니다.\n다시 선택해 주세요.",
                    Toast.LENGTH_SHORT
                ).show()
            }
        } else if (resultCode == ImagePicker.RESULT_ERROR) {
            binding.tvSelectContent.text = "파일 선택"
            viewModel.contentUri = null
            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()
    }

    override fun setupView() {
        loadingDialog = LoadingDialog(this, layoutInflater)

        binding.toolbar.tvBack.text = "콘텐츠 등록"
        binding.toolbar.tvBack.setOnClickListener { finish() }
        binding.llTheme.setOnClickListener {
            if (themeFragment.isAdded) return@setOnClickListener

            themeFragment.show(supportFragmentManager, themeFragment.tag)
        }

        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.tvSelectContent.setOnClickListener {
            val intent = Intent().apply {
                type = "audio/*"
                action = Intent.ACTION_GET_CONTENT
                addCategory(Intent.CATEGORY_OPENABLE)
            }
            selectAudioActivityResultLauncher.launch(
                Intent.createChooser(
                    intent,
                    "Select Audio"
                )
            )
        }

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

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

        binding.tvCancel.setOnClickListener { finish() }
        binding.tvUpload.setOnClickListener {
            viewModel.uploadAudioContent {
                LiveDialog(
                    activity = this,
                    layoutInflater = layoutInflater,
                    title = "콘텐츠 업로드",
                    desc = "등록한 콘텐츠가 업로드 중입니다.\n" +
                        "콘텐츠 등록이 완료되면 알림을 보내드립니다.\n" +
                        "이 페이지를 나가도 콘텐츠는 자동으로 등록됩니다.",
                    confirmButtonTitle = "확인",
                    confirmButtonClick = { finish() },
                ).show(screenWidth)
            }
        }
    }

    private fun checkPermissions() {
        val permissions = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            listOf(Manifest.permission.READ_MEDIA_AUDIO, Manifest.permission.READ_MEDIA_IMAGES)
        } 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()
                }
        )

        compositeDisposable.add(
            binding.etTag.textChanges().skip(1)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe {
                    viewModel.tags = it.toString()
                }
        )

        compositeDisposable.add(
            binding.etSetPrice.textChanges().skip(1)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe {
                    val price = it.toString().toIntOrNull()
                    if (price != null) {
                        viewModel.price = price.toInt()
                    } else {
                        viewModel.price = 0
                        if (it.isNotBlank()) {
                            binding.etSetPrice.setText(it.substring(0, it.length - 1))
                            binding.etSetPrice.setSelection(it.length - 1)
                        }
                    }
                }
        )

        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.isPriceFreeLiveData.observe(this) {
            if (it) {
                viewModel.price = 0
                binding.etSetPrice.setText("0")
                binding.llSetPrice.visibility = View.GONE

                binding.ivPriceFree.visibility = View.VISIBLE
                binding.tvPriceFree.setTextColor(
                    ContextCompat.getColor(
                        applicationContext,
                        R.color.color_eeeeee
                    )
                )
                binding.llPriceFree.setBackgroundResource(R.drawable.bg_round_corner_6_7_9970ff)

                binding.ivPricePaid.visibility = View.GONE
                binding.tvPricePaid.setTextColor(
                    ContextCompat.getColor(
                        applicationContext,
                        R.color.color_9970ff
                    )
                )
                binding.llPricePaid.setBackgroundResource(
                    R.drawable.bg_round_corner_6_7_1f1734_9970ff
                )
            } else {
                binding.llSetPrice.visibility = View.VISIBLE

                binding.ivPricePaid.visibility = View.VISIBLE
                binding.tvPricePaid.setTextColor(
                    ContextCompat.getColor(
                        applicationContext,
                        R.color.color_eeeeee
                    )
                )
                binding.llPricePaid.setBackgroundResource(R.drawable.bg_round_corner_6_7_9970ff)

                binding.ivPriceFree.visibility = View.GONE
                binding.tvPriceFree.setTextColor(
                    ContextCompat.getColor(
                        applicationContext,
                        R.color.color_9970ff
                    )
                )
                binding.llPriceFree.setBackgroundResource(
                    R.drawable.bg_round_corner_6_7_1f1734_9970ff
                )
            }
        }

        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_9970ff)

                binding.ivCommentNo.visibility = View.GONE
                binding.tvCommentNo.setTextColor(
                    ContextCompat.getColor(
                        applicationContext,
                        R.color.color_9970ff
                    )
                )
                binding.llCommentNo.setBackgroundResource(
                    R.drawable.bg_round_corner_6_7_1f1734_9970ff
                )
            } 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_9970ff)

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

        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_1f1734)
                    binding.tvAgeAll.setTextColor(
                        ContextCompat.getColor(
                            applicationContext,
                            R.color.color_9970ff
                        )
                    )

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

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

    private fun getFileName(uri: Uri): String? {
        val scheme = uri.scheme
        var fileName: String? = null

        if (scheme == "content") {
            contentResolver.query(uri, null, null, null, null)?.use { cursor ->
                val nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
                if (nameIndex != -1 && cursor.moveToFirst()) {
                    fileName = cursor.getString(nameIndex)
                }
            }
        } else if (scheme == "file") {
            val file = File(uri.path ?: "")
            fileName = file.name
        }

        return fileName
    }
}
