package com.base.scanqrclear.ui.event

import android.annotation.SuppressLint
import android.content.Intent
import androidx.activity.addCallback
import androidx.core.view.updatePadding
import androidx.core.widget.addTextChangedListener
import com.base.scanqrclear.R
import com.base.scanqrclear.ads.AdsMgr
import com.base.scanqrclear.ads.AdsShowCallBack
import com.base.scanqrclear.base.BaseActivity
import com.base.scanqrclear.bean.ConstObject.appLanguageSp
import com.base.scanqrclear.bean.EventUIBean
import com.base.scanqrclear.bean.config.AdConfigBean
import com.base.scanqrclear.databinding.ActivityEventBinding
import com.base.scanqrclear.utils.BarUtils
import com.base.scanqrclear.utils.LogEx
import com.base.scanqrclear.utils.ToastUtils.toast
import com.google.gson.Gson
import com.kunzisoft.switchdatetime.SwitchDateTimeDialogFragment
import com.kunzisoft.switchdatetime.SwitchDateTimeDialogFragment.OnButtonWithNeutralClickListener
import com.kunzisoft.switchdatetime.SwitchDateTimeDialogFragment.SimpleDateMonthAndDayFormatException
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date
import java.util.GregorianCalendar
import java.util.Locale
import java.util.TimeZone


class EventActivity : BaseActivity<ActivityEventBinding>(ActivityEventBinding::inflate) {

    private val eventUIBean = EventUIBean()
    private var dateTimeFragment: SwitchDateTimeDialogFragment? = null
    private val tagDatetimeFragment: String = "tag_datetime_fragment"
    private var startTime = Date(System.currentTimeMillis())
    private var endTime = Date(System.currentTimeMillis())
    private var setStartOrEnd: Boolean = false//start:true ;end:false

    @SuppressLint("SimpleDateFormat")
    private val dateTimeFormatter = SimpleDateFormat("yyyyMMdd_HHmmss")
    override fun onResumeOneShoot() {
        super.onResumeOneShoot()
        val flag = changeLanguage()
        if (flag) return
    }

    override fun initView() {
        super.initView()
        binding.clTop.updatePadding(top = BarUtils.getStatusBarHeight())
        AdsMgr.showNative(binding.flAd, R.layout.layout_admob_item)
        initDateTimeFragment()
    }

    private fun initDateTimeFragment() {
        dateTimeFragment = supportFragmentManager.findFragmentByTag(tagDatetimeFragment) as SwitchDateTimeDialogFragment?
        if (dateTimeFragment == null) {
            dateTimeFragment = SwitchDateTimeDialogFragment.newInstance(
                getString(R.string.datetime),
                getString(R.string.ok),
                getString(R.string.cancel),
                getString(R.string.clean),  // Optional
                appLanguageSp
            )
        }


        // Optionally define a timezone
        dateTimeFragment?.setTimeZone(TimeZone.getDefault())


        // Assign unmodifiable values
        dateTimeFragment?.set24HoursMode(false)
        dateTimeFragment?.setHighlightAMPMSelection(false)
        dateTimeFragment?.minimumDateTime = GregorianCalendar(1970, Calendar.JANUARY, 1).time
        dateTimeFragment?.maximumDateTime = GregorianCalendar(2200, Calendar.DECEMBER, 30).time

        dateTimeFragment?.setAlertStyle(R.style.DateTimeAlert)

        // Define new day and month format
//        20241230T072300
        try {
            dateTimeFragment?.simpleDateMonthAndDayFormat =
                SimpleDateFormat("MMMM dd", Locale.getDefault())
        } catch (e: SimpleDateMonthAndDayFormatException) {
        }

        // Set listener for date
        // Or use dateTimeFragment.setOnButtonClickListener(new SwitchDateTimeDialogFragment.OnButtonClickListener() {
        dateTimeFragment?.setOnButtonClickListener(object : OnButtonWithNeutralClickListener {
            override fun onPositiveButtonClick(date: Date) {
                val dateTime = dateTimeFormatter.format(startTime).split("_")
                val dateTimeS = dateTime[0] + "T" + dateTime[1]
                kotlin.runCatching {
                    LogEx.logDebug(TAG, "dateTimeS=${dateTimeS}")
                    if (setStartOrEnd) {
                        binding.tvStartDate.text = createDDMMYYYY(date)
                        startTime = date
                        eventUIBean.dtstart = dateTimeS
                    } else {
                        endTime = date
                        if (endTime.before(startTime)) {
                            this@EventActivity.toast("please choose end time", true)
                            endTime = Date(System.currentTimeMillis())
                            return
                        }
                        binding.tvEndDate.text = createDDMMYYYY(date)
                        eventUIBean.dtend = dateTimeS
                    }
                }
            }

            override fun onNegativeButtonClick(date: Date) {
            }

            override fun onNeutralButtonClick(date: Date) {
                if (setStartOrEnd) {
                    binding.tvStartDate.text = this@EventActivity.resources.getString(R.string.begin_time)
                    eventUIBean.dtstart = ""
                } else {
                    binding.tvEndDate.text = this@EventActivity.resources.getString(R.string.end_time)
                    eventUIBean.dtend = ""
                }
            }
        })

    }

    override fun initListener() {
        super.initListener()
        onBackPressedDispatcher.addCallback {
            if (AdConfigBean.adsConfigBean.functionBackShowAd) {
                AdsMgr.showInsert(this@EventActivity, false, object : AdsShowCallBack() {
                    override fun close(where: Int) {
                        finishToMainTop()
                    }

                    override fun failed(where: Int) {
                        finishToMainTop()
                    }

                    override fun googleFailed(where: Int) {
                        finishToMainTop()
                    }
                })
            } else {
                finishToMainTop()
            }
        }
        binding.flBack.setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }
        binding.editName.addTextChangedListener { s ->
            eventUIBean.summary = s.toString()
        }
        binding.editLocation.addTextChangedListener { s ->
            eventUIBean.location = s.toString()
        }
        binding.editDescription.addTextChangedListener { s ->
            eventUIBean.description = s.toString()
        }
        binding.llBeginTime.setOnClickListener {
            val flag = supportFragmentManager.findFragmentByTag(tagDatetimeFragment) != null
            if (dateTimeFragment?.isAdded == true && flag) return@setOnClickListener

            setStartOrEnd = true
            dateTimeFragment?.startAtCalendarView()
            dateTimeFragment?.setDefaultDateTime(startTime)
            dateTimeFragment?.show(supportFragmentManager, tagDatetimeFragment)

        }
        binding.llEndTime.setOnClickListener {
            val flag = supportFragmentManager.findFragmentByTag(tagDatetimeFragment) != null
            if (dateTimeFragment?.isAdded == true && flag) return@setOnClickListener

            setStartOrEnd = false
            dateTimeFragment?.startAtCalendarView()
            dateTimeFragment?.setDefaultDateTime(endTime)
            dateTimeFragment?.show(supportFragmentManager, tagDatetimeFragment)
        }
        binding.flQueren.setOnClickListener {
            if (eventUIBean.summary.isEmpty()) {
                toast("Enter title event", true)
                return@setOnClickListener
            }
            if (eventUIBean.location.isEmpty()) {
                toast("Enter location event", true)
                return@setOnClickListener
            }
            if (eventUIBean.description.isEmpty()) {
                toast("Enter description event", true)
                return@setOnClickListener
            }
            if (eventUIBean.dtstart.isEmpty()) {
                toast("Please choose begin Time", true)
                return@setOnClickListener
            }
            if (eventUIBean.dtend.isEmpty()) {
                toast("Please choose end Time", true)
                return@setOnClickListener
            }

            if (AdConfigBean.adsConfigBean.functionUseShowAd) {
                AdsMgr.showInsert(this, true, object : AdsShowCallBack() {
                    override fun close(where: Int) {
                        jumpCodeActivity()
                    }

                    override fun failed(where: Int) {
                        jumpCodeActivity()
                    }

                    override fun googleFailed(where: Int) {
                        jumpCodeActivity()
                    }
                })
            } else {
                jumpCodeActivity()
            }
        }
    }

    private fun jumpCodeActivity() {
        startActivity(Intent(this, EventCodeActivity::class.java).apply {
            eventUIBean.startTime = startTime.time
            eventUIBean.endTime = endTime.time
            putExtra("data", Gson().toJson(eventUIBean))
        })
        finish()
    }

    fun createDDMMYYYY(date: Date): String {
        val format = SimpleDateFormat("dd/MMMM/yyyy", Locale.ENGLISH)
        return format.format(date)
    }

}