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

import android.Manifest
import android.annotation.SuppressLint
import android.app.DatePickerDialog
import android.app.TimePickerDialog
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.PurchaseOption
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.dialog.SodaLiveTimePickerDialog
import kr.co.vividnext.sodalive.extensions.convertDateFormat
import kr.co.vividnext.sodalive.extensions.dpToPx
import org.koin.android.ext.android.inject
import java.io.File
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date
import java.util.Locale

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()
        }
    }

    private val datePickerDialogListener =
        DatePickerDialog.OnDateSetListener { _, year, monthOfYear, dayOfMonth ->
            viewModel.releaseDate = String.format("%d-%02d-%02d", year, monthOfYear + 1, dayOfMonth)
            viewModel.setReservationDate(
                String.format(
                    "%d.%02d.%02d",
                    year,
                    monthOfYear + 1,
                    dayOfMonth
                )
            )
        }

    private val timePickerDialogListener =
        TimePickerDialog.OnTimeSetListener { _, hourOfDay, minute ->
            val timeString = String.format("%02d:%02d", hourOfDay, minute)
            viewModel.releaseTime = timeString
            viewModel.setReservationTime(timeString.convertDateFormat("HH:mm", "a hh:mm"))
        }

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

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

        bindData()
    }

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

        binding.tvServiceDate.text = if (SharedPreferenceManager.userId == 17958L) {
            "※ 이용기간 : 대여(15일) | 소장(이용 기간 1년)"
        } else {
            "※ 이용기간 : 대여(15일) | 소장(서비스 종료시까지)"
        }
        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.llPreviewYes.setOnClickListener { viewModel.setGeneratePreview(true) }
        binding.llPreviewNo.setOnClickListener { viewModel.setGeneratePreview(false) }
        binding.llLimited.setOnClickListener { viewModel.setLimited(true) }
        binding.llNotLimited.setOnClickListener { viewModel.setLimited(false) }
        binding.llBoth.setOnClickListener { viewModel.setPurchaseOption(PurchaseOption.BOTH) }
        binding.llBuyOnly.setOnClickListener { viewModel.setPurchaseOption(PurchaseOption.BUY_ONLY) }
        binding.llRentOnly.setOnClickListener {
            viewModel.setPurchaseOption(PurchaseOption.RENT_ONLY)
        }
        binding.llCommentNo.setOnClickListener { viewModel.setAvailableComment(false) }
        binding.llCommentYes.setOnClickListener { viewModel.setAvailableComment(true) }
        binding.llActiveNow.setOnClickListener { viewModel.setActiveReservation(false) }
        binding.llActiveReservation.setOnClickListener { viewModel.setActiveReservation(true) }

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

        binding.tvReservationDate.setOnClickListener {
            val reservationDate = viewModel.releaseDate.split("-")
            val datePicker: DatePickerDialog

            if (reservationDate.isNotEmpty() && reservationDate.size == 3) {
                datePicker = DatePickerDialog(
                    this,
                    R.style.DatePickerStyle,
                    datePickerDialogListener,
                    reservationDate[0].toInt(),
                    reservationDate[1].toInt() - 1,
                    reservationDate[2].toInt()
                )
            } else {
                val dateString = SimpleDateFormat(
                    "yyyy.MM.dd",
                    Locale.getDefault()
                ).format(Date()).split(".")

                datePicker = DatePickerDialog(
                    this,
                    R.style.DatePickerStyle,
                    datePickerDialogListener,
                    dateString[0].toInt(),
                    dateString[1].toInt() - 1,
                    dateString[2].toInt()
                )
            }

            datePicker.show()
        }

        binding.tvReservationTime.setOnClickListener {
            val reservationTime = viewModel.releaseTime.split(":")
            val timePicker: TimePickerDialog

            if (reservationTime.isNotEmpty() && reservationTime.size == 2) {
                timePicker = SodaLiveTimePickerDialog(
                    this,
                    R.style.TimePickerStyle,
                    timePickerDialogListener,
                    reservationTime[0].toInt(),
                    reservationTime[1].toInt(),
                    false
                )
            } else {
                val calendar = Calendar.getInstance().apply {
                    add(Calendar.HOUR_OF_DAY, 1)
                }
                val initialHour = calendar.get(Calendar.HOUR_OF_DAY)
                val initialMinute = calendar.get(Calendar.MINUTE) / 15 * 15

                timePicker = SodaLiveTimePickerDialog(
                    this,
                    R.style.TimePickerStyle,
                    timePickerDialogListener,
                    initialHour,
                    initialMinute,
                    false
                )
            }

            timePicker.show()
        }
    }

    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()
                }
        )

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

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

        compositeDisposable.add(
            binding.etPreviewStartTime.textChanges().skip(1)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe {
                    if (it.isNotBlank()) {
                        viewModel.previewStartTime = it.toString()
                    } else {
                        viewModel.previewStartTime = null
                    }
                }
        )

        compositeDisposable.add(
            binding.etPreviewEndTime.textChanges().skip(1)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe {
                    if (it.isNotBlank()) {
                        viewModel.previewEndTime = it.toString()
                    } else {
                        viewModel.previewEndTime = null
                    }
                }
        )

        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) {
                checkPriceFree()
            } else {
                checkPricePaid()
            }
        }

        viewModel.isLimitedLiveData.observe(this) {
            if (it) {
                checkLimited()
            } else {
                checkNotLimited()
            }
        }

        viewModel.isGeneratePreviewLiveData.observe(this) {
            if (it) {
                checkGeneratePreview()
            } else {
                checkNotGeneratePreview()
            }
        }

        viewModel.purchaseOptionLiveData.observe(this) {
            when (it) {
                PurchaseOption.BOTH -> checkBoth()
                PurchaseOption.BUY_ONLY -> checkBuyOnly()
                PurchaseOption.RENT_ONLY -> checkRentOnly()
            }
        }

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

        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_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
                        )
                    )
                }
            }
        }

        viewModel.isActiveReservationLiveData.observe(this) {
            if (it) {
                checkActiveReservation()
            } else {
                checkActiveNow()
            }
        }

        viewModel.reservationDateLiveData.observe(this) {
            binding.tvReservationDate.text = it
        }

        viewModel.reservationTimeLiveData.observe(this) {
            binding.tvReservationTime.text = it
        }

        viewModel.isShowConfigLimitedLiveData.observe(this) {
            if (it) {
                binding.llConfigLimited.visibility = View.VISIBLE
                binding.tvConfigLimitedTitle.visibility = View.VISIBLE
            } else {
                binding.llConfigLimited.visibility = View.GONE
                binding.tvConfigLimitedTitle.visibility = View.GONE
                binding.etLimited.visibility = View.GONE
                binding.etLimited.setText("")
            }
        }
    }

    private fun checkActiveNow() {
        binding.llReservationDatetime.visibility = View.GONE

        binding.ivActiveNow.visibility = View.VISIBLE
        binding.tvActiveNow.setTextColor(
            ContextCompat.getColor(
                applicationContext,
                R.color.color_eeeeee
            )
        )
        binding.llActiveNow.setBackgroundResource(R.drawable.bg_round_corner_6_7_3bb9f1)

        binding.ivActiveReservation.visibility = View.GONE
        binding.tvActiveReservation.setTextColor(
            ContextCompat.getColor(
                applicationContext,
                R.color.color_3bb9f1
            )
        )
        binding.llActiveReservation.setBackgroundResource(
            R.drawable.bg_round_corner_6_7_13181b
        )
    }

    private fun checkActiveReservation() {
        binding.llReservationDatetime.visibility = View.VISIBLE
        binding.ivActiveReservation.visibility = View.VISIBLE
        binding.tvActiveReservation.setTextColor(
            ContextCompat.getColor(
                applicationContext,
                R.color.color_eeeeee
            )
        )
        binding.llActiveReservation.setBackgroundResource(R.drawable.bg_round_corner_6_7_3bb9f1)

        binding.ivActiveNow.visibility = View.GONE
        binding.tvActiveNow.setTextColor(
            ContextCompat.getColor(
                applicationContext,
                R.color.color_3bb9f1
            )
        )
        binding.llActiveNow.setBackgroundResource(
            R.drawable.bg_round_corner_6_7_13181b
        )
    }

    private fun checkPriceFree() {
        viewModel.price = 0
        binding.etSetPrice.setText("0")
        binding.llSetPrice.visibility = View.GONE
        binding.llConfigPurchase.visibility = View.GONE
        binding.tvTitleConfigKeep.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_3bb9f1)

        binding.ivPricePaid.visibility = View.GONE
        binding.tvPricePaid.setTextColor(
            ContextCompat.getColor(
                applicationContext,
                R.color.color_3bb9f1
            )
        )
        binding.llPricePaid.setBackgroundResource(
            R.drawable.bg_round_corner_6_7_13181b
        )

        binding.llConfigPreview.visibility = View.GONE
        binding.llConfigPreviewTime.visibility = View.GONE
    }

    private fun checkPricePaid() {
        binding.llSetPrice.visibility = View.VISIBLE
        binding.llConfigPurchase.visibility = View.VISIBLE
        binding.tvTitleConfigKeep.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_3bb9f1)

        binding.ivPriceFree.visibility = View.GONE
        binding.tvPriceFree.setTextColor(
            ContextCompat.getColor(
                applicationContext,
                R.color.color_3bb9f1
            )
        )
        binding.llPriceFree.setBackgroundResource(
            R.drawable.bg_round_corner_6_7_13181b
        )
        binding.llConfigPreview.visibility = View.VISIBLE
    }

    private fun checkNotLimited() {
        binding.ivNotLimited.visibility = View.VISIBLE
        binding.tvNotLimited.setTextColor(
            ContextCompat.getColor(
                applicationContext,
                R.color.color_eeeeee
            )
        )
        binding.llNotLimited.setBackgroundResource(R.drawable.bg_round_corner_6_7_3bb9f1)

        binding.ivLimited.visibility = View.GONE
        binding.tvLimited.setTextColor(
            ContextCompat.getColor(
                applicationContext,
                R.color.color_3bb9f1
            )
        )
        binding.llLimited.setBackgroundResource(
            R.drawable.bg_round_corner_6_7_13181b
        )
        binding.etLimited.visibility = View.GONE
        binding.etLimited.setText("")
    }

    private fun checkLimited() {
        binding.ivLimited.visibility = View.VISIBLE
        binding.tvLimited.setTextColor(
            ContextCompat.getColor(
                applicationContext,
                R.color.color_eeeeee
            )
        )
        binding.llLimited.setBackgroundResource(R.drawable.bg_round_corner_6_7_3bb9f1)

        binding.ivNotLimited.visibility = View.GONE
        binding.tvNotLimited.setTextColor(
            ContextCompat.getColor(
                applicationContext,
                R.color.color_3bb9f1
            )
        )
        binding.llNotLimited.setBackgroundResource(
            R.drawable.bg_round_corner_6_7_13181b
        )
        binding.etLimited.visibility = View.VISIBLE
    }

    private fun checkGeneratePreview() {
        binding.ivPreviewYes.visibility = View.VISIBLE
        binding.tvPreviewYes.setTextColor(
            ContextCompat.getColor(
                applicationContext,
                R.color.color_eeeeee
            )
        )
        binding.llPreviewYes.setBackgroundResource(R.drawable.bg_round_corner_6_7_3bb9f1)

        binding.ivPreviewNo.visibility = View.GONE
        binding.tvPreviewNo.setTextColor(
            ContextCompat.getColor(
                applicationContext,
                R.color.color_3bb9f1
            )
        )
        binding.llPreviewNo.setBackgroundResource(
            R.drawable.bg_round_corner_6_7_13181b
        )
        binding.llConfigPreviewTime.visibility = View.VISIBLE
    }

    private fun checkNotGeneratePreview() {
        binding.ivPreviewNo.visibility = View.VISIBLE
        binding.tvPreviewNo.setTextColor(
            ContextCompat.getColor(
                applicationContext,
                R.color.color_eeeeee
            )
        )
        binding.llPreviewNo.setBackgroundResource(R.drawable.bg_round_corner_6_7_3bb9f1)

        binding.ivPreviewYes.visibility = View.GONE
        binding.tvPreviewYes.setTextColor(
            ContextCompat.getColor(
                applicationContext,
                R.color.color_3bb9f1
            )
        )
        binding.llPreviewYes.setBackgroundResource(
            R.drawable.bg_round_corner_6_7_13181b
        )
        binding.llConfigPreviewTime.visibility = View.GONE
    }

    private fun uncheckPurchaseOption() {
        binding.ivBoth.visibility = View.GONE
        binding.ivBuyOnly.visibility = View.GONE
        binding.ivRentOnly.visibility = View.GONE

        binding.tvBoth.setTextColor(
            ContextCompat.getColor(
                applicationContext,
                R.color.color_3bb9f1
            )
        )
        binding.llBoth.setBackgroundResource(R.drawable.bg_round_corner_6_7_13181b)

        binding.tvBuyOnly.setTextColor(
            ContextCompat.getColor(
                applicationContext,
                R.color.color_3bb9f1
            )
        )
        binding.llBuyOnly.setBackgroundResource(R.drawable.bg_round_corner_6_7_13181b)

        binding.tvRentOnly.setTextColor(
            ContextCompat.getColor(
                applicationContext,
                R.color.color_3bb9f1
            )
        )
        binding.llRentOnly.setBackgroundResource(R.drawable.bg_round_corner_6_7_13181b)
    }

    private fun checkBoth() {
        uncheckPurchaseOption()
        binding.tvPriceTitle.text = "소장 가격"
        binding.ivBoth.visibility = View.VISIBLE
        binding.tvBoth.setTextColor(
            ContextCompat.getColor(
                applicationContext,
                R.color.color_eeeeee
            )
        )
        binding.llBoth.setBackgroundResource(R.drawable.bg_round_corner_6_7_3bb9f1)
    }

    private fun checkBuyOnly() {
        uncheckPurchaseOption()
        binding.tvPriceTitle.text = "소장 가격"
        binding.ivBuyOnly.visibility = View.VISIBLE
        binding.tvBuyOnly.setTextColor(
            ContextCompat.getColor(
                applicationContext,
                R.color.color_eeeeee
            )
        )
        binding.llBuyOnly.setBackgroundResource(R.drawable.bg_round_corner_6_7_3bb9f1)
    }

    private fun checkRentOnly() {
        uncheckPurchaseOption()
        binding.tvPriceTitle.text = "대여 가격"
        binding.ivRentOnly.visibility = View.VISIBLE
        binding.tvRentOnly.setTextColor(
            ContextCompat.getColor(
                applicationContext,
                R.color.color_eeeeee
            )
        )
        binding.llRentOnly.setBackgroundResource(R.drawable.bg_round_corner_6_7_3bb9f1)
    }

    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
    }
}
