package com.halo.assistant.fragment.reserve

import android.content.Context
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import com.gh.common.dialog.ReserveReminderPhoneNumberDialog
import com.gh.common.dialog.ReserveReminderPhoneNumberDialog.Companion.DIALOG_TYPE_BIND_PHONE
import com.gh.common.dialog.ReserveReminderPhoneNumberDialog.Companion.DIALOG_TYPE_CHANGE_PHONE
import com.gh.common.dialog.ReserveReminderPhoneNumberDialog.Companion.DIALOG_TYPE_VERIFY_PHONE
import com.gh.common.dialog.ReserveSuccessReminderDialog
import com.gh.gamecenter.ShellActivity
import com.gh.gamecenter.ShellActivity.Companion.getIntent
import com.gh.gamecenter.WebActivity
import com.gh.gamecenter.common.constant.Constants
import com.gh.gamecenter.common.entity.WechatConfigEntity
import com.gh.gamecenter.common.utils.PermissionHelper
import com.gh.gamecenter.common.utils.SensorsBridge
import com.gh.gamecenter.common.utils.toObject
import com.gh.gamecenter.core.utils.CurrentActivityHolder
import com.gh.gamecenter.core.utils.SPUtils
import com.gh.gamecenter.entity.ReserveReminderEntity
import com.gh.gamecenter.feature.entity.GameEntity
import com.gh.gamecenter.livedata.EventObserver

class ReserveReminderContainerFragment : Fragment(), OnReserveReminderListener {

    private var isWechatBinding = false

    private var isCanDismissed = true

    private val repository by lazy {
        ReserveReminderRepository.newInstance()
    }

    private val viewModel by viewModels<ReserveReminderViewModel>()

    private lateinit var reserveReminderEntity: ReserveReminderEntity
    private var game: GameEntity? = null

    private val reservesReminderDialog by lazy {
        ReserveSuccessReminderDialog.create(requireContext(), this).apply {
            setOnDismissListener {
                if (isCanDismissed) {
                    onDismiss()
                }
            }
        }
    }

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

        game = arguments?.getParcelable(KEY_GAME)
        reserveReminderEntity =
            arguments?.getParcelable(KEY_RESERVE_REMINDER) ?: ReserveReminderEntity()

        viewModel.updateReserveReminder(reserveReminderEntity)
        reservesReminderDialog.show()

        with(viewModel) {
            val lifeCycleOwner = this@ReserveReminderContainerFragment
            reserveReminder.observe(lifeCycleOwner) {
                reservesReminderDialog.updateReserveReminder(it)
            }

            sendVerifyCode.observe(lifeCycleOwner, EventObserver {
                showPhoneNumberDialog(DIALOG_TYPE_VERIFY_PHONE, reserveReminderEntity.smsConfig.mobile, it)
            })

            unableSmsReminderSuccessfully.observe(lifeCycleOwner, EventObserver {
                reserveReminderEntity.smsConfig.notice = false
                reserveReminderEntity.smsConfig.mobileValidated = false
                viewModel.updateReserveReminder(reserveReminderEntity)
            })
        }
    }

    override fun updateSmsReminder(isEnable: Boolean) {
        if (isEnable) {
            trackAppointmentSuccessDialogClick("开启短信提醒")
            showPhoneNumberDialog(DIALOG_TYPE_BIND_PHONE, reserveReminderEntity.smsConfig.mobile)
        } else {
            trackAppointmentSuccessDialogClick("关闭短信提醒")
            viewModel.unableSmsReminder(game?.id ?: "")
        }

    }

    override fun updateWechatReminder() {
        isWechatBinding = true
        trackAppointmentSuccessDialogClick("开启微信提醒")
        startActivity(WebActivity.getBindWechatIntent(requireContext()))
    }

    override fun changedPhoneNumber() {
        trackAppointmentSuccessDialogClick("修改手机号")
        showPhoneNumberDialog(DIALOG_TYPE_CHANGE_PHONE, reserveReminderEntity.smsConfig.mobile)
    }

    override fun verifyPhoneNumber() {
        trackAppointmentSuccessDialogClick("验证手机号")
        viewModel.sendVerifyCode(reserveReminderEntity.smsConfig.mobile)
    }

    override fun changeWechatBinding() {
        isWechatBinding = true
        trackAppointmentSuccessDialogClick("更换绑定微信")
        startActivity(WebActivity.getBindWechatIntent(requireContext()))
    }

    override fun bindPhoneSuccessfully(hasValidated: Boolean, phone: String) {
        reserveReminderEntity.smsConfig =
            ReserveReminderEntity.SmsConfig(_notice = true, _mobile = phone, _mobileValidated = hasValidated)

        viewModel.updateReserveReminder(reserveReminderEntity)
    }

    override fun phoneNumberValidateSuccessfully() {
        reserveReminderEntity.smsConfig.mobileValidated = true
        viewModel.updateReserveReminder(reserveReminderEntity)
    }

    override fun enableAutoDownload(isEnable: Boolean) {
        viewModel.enableAutoDownload(game, isEnable)
    }

    override fun realName() {
        trackAppointmentSuccessDialogClick("实名认证")
        val intent = getIntent(requireContext(), ShellActivity.Type.REAL_NAME_INFO)
        requireContext().startActivity(intent)
    }

    override fun updateCalendarReminder() {
        trackAppointmentSuccessDialogClick("开启日历提醒")
        PermissionHelper.checkCalendarPermissions(this, game?.id ?: "", game?.name ?: "", game?.categoryChinese ?: "") {
            viewModel.addCalendarEvent(game?.id ?: "", reserveReminderEntity.calendarConfig)
        }
    }


    private fun showPhoneNumberDialog(dialogType: Int, phone: String, serviceId: String = "") {
        isCanDismissed = false
        reservesReminderDialog.dismiss()
        ReserveReminderPhoneNumberDialog.create(
            requireContext(),
            dialogType,
            phone,
            serviceId,
            game?.id ?: "",
            repository,
            this
        )
            .let {
                it.show()
                it.setOnDismissListener {
                    isCanDismissed = true
                    reservesReminderDialog.show()
                }
            }
    }

    override fun onResume() {
        super.onResume()
        if (isWechatBinding) {
            isWechatBinding = false
            val wechatConfig = SPUtils.getString(Constants.SP_WECHAT_CONFIG).toObject<WechatConfigEntity>()
            if (reserveReminderEntity.wechatConfig.bind != wechatConfig?.bind
                || reserveReminderEntity.wechatConfig.notice != wechatConfig.notice
                || reserveReminderEntity.wechatConfig.follow != wechatConfig.follow
                || reserveReminderEntity.wechatConfig.nickName != wechatConfig.nickName
            ) {
                reserveReminderEntity.wechatConfig = wechatConfig ?: WechatConfigEntity()
                viewModel.updateReserveReminder(reserveReminderEntity)
            }
        }
    }


    private fun onDismiss() {
        SensorsBridge.trackAppointmentSuccessDialogClick(
            game?.id ?: "",
            game?.name ?: "",
            game?.categoryChinese ?: "",
            "关闭弹窗",
            wechatRemind = reserveReminderEntity.wechatConfig.isReminderEnable,
            messageRemind = if (reserveReminderEntity.hasSmsConfig) reserveReminderEntity.smsConfig.notice else null,
            automaticDownload = reserveReminderEntity.isEnableAutoDownload,
            calendarRemind = if (reserveReminderEntity.hasCalendarConfig) reserveReminderEntity.calendarConfig.notice else null
        )
        val ft = parentFragmentManager.beginTransaction()
        ft.remove(this)
        ft.commitAllowingStateLoss()
    }

    private fun trackAppointmentSuccessDialogClick(
        buttonName: String,
        wechatRemind: Boolean? = null,
        messageRemind: Boolean? = null,
        autoDownloadEnable: Boolean? = null
    ) {
        SensorsBridge.trackAppointmentSuccessDialogClick(
            game?.id ?: "",
            game?.name ?: "",
            game?.categoryChinese ?: "",
            buttonName,
            wechatRemind,
            messageRemind,
            autoDownloadEnable
        )
    }


    companion object {

        private const val KEY_RESERVE_REMINDER = "key_reserve_reminder"
        private const val KEY_GAME = "key_game"

        @JvmStatic
        fun show(context: Context, gameEntity: GameEntity?, reserveReminder: ReserveReminderEntity) {
            (if (context is AppCompatActivity) {
                context.supportFragmentManager
            } else {
                (CurrentActivityHolder.getCurrentActivity() as? AppCompatActivity)?.supportFragmentManager
            })?.let {
                val tag = ReserveReminderContainerFragment::class.java.name
                val fragment = it.findFragmentByTag(tag) ?: newInstance(gameEntity, reserveReminder)
                if (!fragment.isAdded) {
                    it.beginTransaction()
                        .add(fragment, tag)
                        .commitAllowingStateLoss()
                }
            }
        }

        private fun newInstance(
            gameEntity: GameEntity?,
            reserveReminder: ReserveReminderEntity
        ): ReserveReminderContainerFragment {
            return ReserveReminderContainerFragment().apply {
                arguments = Bundle().apply {
                    putParcelable(KEY_GAME, gameEntity)
                    putParcelable(KEY_RESERVE_REMINDER, reserveReminder)
                }
            }
        }
    }
}

interface OnReserveReminderListener {

    fun updateSmsReminder(isEnable: Boolean)

    fun updateWechatReminder()

    fun bindPhoneSuccessfully(hasValidated: Boolean, phone: String)

    fun changedPhoneNumber()

    fun verifyPhoneNumber()

    fun changeWechatBinding()

    fun phoneNumberValidateSuccessfully()

    fun enableAutoDownload(isEnable: Boolean)

    fun realName()

    fun updateCalendarReminder()
}