package com.gh.common.dialog

import android.content.Context
import android.os.Bundle
import android.os.Parcelable
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import com.gh.common.util.DirectUtils
import com.gh.gamecenter.R
import com.gh.gamecenter.common.HaloApp
import com.gh.gamecenter.common.base.fragment.BaseDialogFragment
import com.gh.gamecenter.common.constant.Constants
import com.gh.gamecenter.common.utils.SensorsBridge
import com.gh.gamecenter.common.utils.dip2px
import com.gh.gamecenter.core.utils.CurrentActivityHolder
import com.gh.gamecenter.core.utils.SPUtils
import com.gh.gamecenter.databinding.DialogFragmentAccelerateExporationBinding
import kotlinx.parcelize.Parcelize

public class AccelerateExpirationDialogFragment : BaseDialogFragment() {

    private lateinit var binding: DialogFragmentAccelerateExporationBinding

    private var _reminder: ExpirationReminder? = null

    override fun onBack(): Boolean {
        return true
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        _reminder = arguments?.getParcelable(KEY_EXPIRATION_REMINDER)
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return DialogFragmentAccelerateExporationBinding.inflate(inflater, container, false)
            .also {
                binding = it
            }.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        val reminder = _reminder ?: return
        val (title, content) = when (reminder) {
            is ExpirationReminder.UserExpired -> {
                SensorsBridge.trackMonthlyPackageExpiresDialogShow(
                    reminder.gameId, reminder.gameName, reminder.pkgName, reminder.sourceEntrance
                )
                getString(
                    R.string.membership_expiration_reminder_title,
                    "${reminder.days}"
                ) to getString(R.string.membership_expiration_reminder_content)
            }

            is ExpirationReminder.InsufficientDuration -> {
                SensorsBridge.trackInsufficientDurationDialogShow(
                    reminder.gameId,
                    reminder.gameName,
                    reminder.pkgName,
                    reminder.sourceEntrance
                )
                getString(
                    R.string.duration_time_out_reminder_title,
                    "${reminder.hours}"
                ) to getString(R.string.duration_time_out_reminder_content)
            }

            is ExpirationReminder.DurationExpired -> {
                SensorsBridge.trackTimedPackageExpiresDialogShow(
                    reminder.gameId,
                    reminder.gameName,
                    reminder.pkgName,
                    reminder.sourceEntrance
                )
                getString(
                    R.string.duration_expiration_reminder_title,
                    "${reminder.days}"
                ) to getString(R.string.duration_expiration_reminder_content)
            }

            is ExpirationReminder.TimeRunsOut -> {
                SensorsBridge.trackDurationExhaustedDialogShow()
                getString(R.string.accelerator_member_expired_title) to getString(R.string.accelerator_member_expired_content)
            }
        }

        binding.tvTitle.text = title
        binding.tvContent.text = content
        binding.tvCancel.setOnClickListener {
            when (reminder) {
                is ExpirationReminder.UserExpired -> {
                    SensorsBridge.trackMonthlyPackageExpiresDialogClick(
                        reminder.gameId, reminder.gameName, reminder.pkgName, reminder.sourceEntrance, BUTTON_NAME_KNOW
                    )
                }

                is ExpirationReminder.InsufficientDuration -> {
                    SensorsBridge.trackInsufficientDurationDialogClick(
                        reminder.gameId, reminder.gameName, reminder.pkgName, reminder.sourceEntrance, BUTTON_NAME_KNOW
                    )
                }

                is ExpirationReminder.DurationExpired -> {
                    SensorsBridge.trackTimedPackageExpiresDialogClick(
                        reminder.gameId, reminder.gameName, reminder.pkgName, reminder.sourceEntrance, BUTTON_NAME_KNOW
                    )
                }

                is ExpirationReminder.TimeRunsOut -> {
                    SensorsBridge.trackDurationExhaustedDialogClick(BUTTON_NAME_KNOW)
                }
            }
            dismissAllowingStateLoss()
        }
        binding.tvSubmit.setOnClickListener {
            when (reminder) {
                is ExpirationReminder.UserExpired -> {
                    SensorsBridge.trackMonthlyPackageExpiresDialogClick(
                        reminder.gameId, reminder.gameName, reminder.pkgName, reminder.sourceEntrance, BUTTON_NAME_BUY
                    )
                }

                is ExpirationReminder.InsufficientDuration -> {
                    SensorsBridge.trackInsufficientDurationDialogClick(
                        reminder.gameId, reminder.gameName, reminder.pkgName, reminder.sourceEntrance, BUTTON_NAME_BUY
                    )
                }

                is ExpirationReminder.DurationExpired -> {
                    SensorsBridge.trackTimedPackageExpiresDialogClick(
                        reminder.gameId, reminder.gameName, reminder.pkgName, reminder.sourceEntrance, BUTTON_NAME_BUY
                    )
                }

                is ExpirationReminder.TimeRunsOut -> {
                    SensorsBridge.trackDurationExhaustedDialogClick(BUTTON_NAME_BUY)
                }
            }
            SensorsBridge.trackMyAssetsPageShow(
                reminder.pkgName,
                reminder.gameId,
                reminder.gameName,
                reminder.dialogName
            )
            dismissAllowingStateLoss()

            DirectUtils.navigateToMyAssetsPage(requireContext(), reminder.sourceEntrance)
        }
    }

    override fun onStart() {
        super.onStart()
        val width = HaloApp.getInstance().resources.displayMetrics.widthPixels - 60F.dip2px()
        val height = dialog?.window?.attributes?.height ?: ViewGroup.LayoutParams.WRAP_CONTENT
        dialog?.window?.setLayout(width, height)
    }

    companion object {
        const val KEY_EXPIRATION_REMINDER = "key_expiration_reminder"

        private const val BUTTON_NAME_KNOW = "知道了"
        private const val BUTTON_NAME_BUY = "前往购买"

        fun checkDialogShown(context: Context, reminder: ExpirationReminder, callback: ((Boolean) -> Unit)? = null) {

            when (reminder) {
                is ExpirationReminder.UserExpired -> {
                    val days = SPUtils.getLong(Constants.SP_ACCELERATOR_USER_REMAINING_REMIND)
                    if (reminder.days != days) {
                        SPUtils.setLong(Constants.SP_ACCELERATOR_USER_REMAINING_REMIND, reminder.days)
                        show(context, reminder)
                        callback?.invoke(true)
                    } else {
                        callback?.invoke(false)
                    }
                }

                is ExpirationReminder.InsufficientDuration -> {
                    val hours = SPUtils.getLong(Constants.SP_ACCELERATOR_DURATION_REMAINING_HOURS)
                    if (reminder.hours != hours) {
                        SPUtils.setLong(Constants.SP_ACCELERATOR_DURATION_REMAINING_HOURS, reminder.hours)
                        show(context, reminder)
                        callback?.invoke(true)
                    } else {
                        callback?.invoke(false)
                    }
                }

                is ExpirationReminder.DurationExpired -> {
                    val days = SPUtils.getLong(Constants.SP_ACCELERATOR_DURATION_REMAINING_DAYS)
                    if (reminder.days != days) {
                        SPUtils.setLong(Constants.SP_ACCELERATOR_DURATION_REMAINING_DAYS, reminder.days)
                        show(context, reminder)
                        callback?.invoke(true)
                    } else {
                        callback?.invoke(false)
                    }
                }

                is ExpirationReminder.TimeRunsOut -> {
                    val hasShow = SPUtils.getBoolean(Constants.SP_ACCELERATOR_MEMBERSHIP_EXPIRED)
                    if (!hasShow) {
                        SPUtils.setBoolean(Constants.SP_ACCELERATOR_MEMBERSHIP_EXPIRED, true)
                        show(context, reminder)
                        callback?.invoke(true)
                    } else {
                        callback?.invoke(false)
                    }
                }
            }
        }

        fun show(context: Context, reminder: ExpirationReminder) {
            if (context is AppCompatActivity) {
                context.supportFragmentManager
            } else {
                (CurrentActivityHolder.getCurrentActivity() as? AppCompatActivity)?.supportFragmentManager
            }?.let {
                val fragment = AccelerateExpirationDialogFragment().apply {
                    arguments = Bundle().apply {
                        putParcelable(KEY_EXPIRATION_REMINDER, reminder)
                    }
                }
                fragment.show(it, AcceleratorPermissionGuideDialogFragment::class.java.name)
            }
        }
    }

    sealed class ExpirationReminder(
        val gameId: String,
        val gameName: String,
        val pkgName: String,
        val sourceEntrance: String
    ) :
        Parcelable {

        abstract val dialogName: String

        @Parcelize
        data class InsufficientDuration(
            val hours: Long,
            private val _gameId: String,
            private val _gameName: String,
            private val _pkgName: String,
            private val _sourceEntrance: String,
        ) :
            ExpirationReminder(_gameId, _gameName, _pkgName, _sourceEntrance) {

            override val dialogName: String
                get() = "时长不足提示弹窗"
        }

        @Parcelize
        data class DurationExpired(
            val days: Long,
            private val _gameId: String,
            private val _gameName: String,
            private val _pkgName: String,
            private val _sourceEntrance: String,
        ) :
            ExpirationReminder(_gameId, _gameName, _pkgName, _sourceEntrance) {

            override val dialogName: String
                get() = "计时套餐临期提示弹窗"
        }

        @Parcelize
        data class UserExpired(
            val days: Long,
            private val _gameId: String,
            private val _gameName: String,
            private val _pkgName: String,
            private val _sourceEntrance: String,
        ) :
            ExpirationReminder(_gameId, _gameName, _pkgName, _sourceEntrance) {

            override val dialogName: String
                get() = "包月套餐临期提示弹窗"
        }

        @Parcelize
        data class TimeRunsOut(
            private val _sourceEntrance: String,
        ) : ExpirationReminder("", "", "", _sourceEntrance) {

            override val dialogName: String
                get() = "时长耗尽提示弹窗"
        }
    }
}