package com.mobiuz.app.dev.ui.service

import android.Manifest
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.telephony.PhoneStateListener
import android.telephony.TelephonyManager
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.isVisible
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import com.mobiuz.app.databinding.BottomSheetUssdBinding
import com.mobiuz.app.dev.model.SharedPref
import com.mobiuz.app.dev.model.UssdData
import com.mobiuz.app.dev.ui.global.ButtonClick
import com.mobiuz.app.dev.utils.extensions.getCurrentName
import com.mobiuz.app.dev.utils.extensions.checkPermission
import com.mobiuz.app.dev.utils.extensions.customLog
import dagger.hilt.android.AndroidEntryPoint
import dagger.hilt.android.qualifiers.ApplicationContext
import javax.inject.Inject

@AndroidEntryPoint
class UssdBottomSheetDialog(val data: UssdData) : BottomSheetDialogFragment() {

    @Inject
    lateinit var pref: SharedPref
    private var _bn: BottomSheetUssdBinding? = null
    private val bn get() = _bn ?: throw NullPointerException("cannot inflate")
    private var lng = ""

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        _bn = BottomSheetUssdBinding.inflate(inflater)
        return bn.root
    }

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

    private fun setUpUI() {
        bn.apply {
            lng = pref.language
            data.apply {
                txtTitle.text = this.title.getCurrentName(lng)
                val dec = this.short_description.getCurrentName(lng)
                txtDescription.isVisible = dec.isNotEmpty()
                txtDescription.text = dec
                txtCode.text = this.code
            }
            btnZapros.setOnClickListener(object : ButtonClick() {
                override fun onSingleClick(v: View?) {
                    pref.isShowPin = false
                    checkPermission(Manifest.permission.CALL_PHONE) {
                        try {
                            pref.blockedTime = System.currentTimeMillis()
                            pref.isShowPin = false
                            val ussd = data.code.replace("#", "") + Uri.encode("#")
                            val intent = Intent(Intent.ACTION_CALL, Uri.parse("tel:$ussd"))
                            startActivity(intent)

                        } catch (e: Exception) {
                            pref.isShowPin = false
                        }
                        dismiss()
                    }
                }
            })
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        _bn = null
    }

}

