package com.seatel.mobilehall.ui.home.fragment

import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.app.Dialog
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.view.View
import androidx.annotation.RequiresApi
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import com.seatel.mobilehall.R
import com.seatel.mobilehall.databinding.DialogSupportBinding
import com.seatel.mobilehall.ui.login.model.ContactService
import com.seatel.mobilehall.ui.profile.interactor.BottomSheetInteractor
import com.seatel.mobilehall.util.PermissionUtil

class SupportBottomSheetFragment(
    var contactService: ArrayList<ContactService>
) : BottomSheetDialogFragment(), View.OnClickListener {

    private var mParams: CoordinatorLayout.LayoutParams? = null
    private lateinit var bottomSheetBehavior: BottomSheetBehavior<*>
    private lateinit var mBottomSheetView: BottomSheetInteractor.View
    private var strPhone = ""
    private var messenger = ""
    private var website = ""
    private lateinit var mPhoneNumberRequest: PermissionUtil.PermissionRequestObject


    private var _binding: DialogSupportBinding? = null
    private val binding get() = _binding!!

    private val mBottomSheetBehaviorCallback = object : BottomSheetBehavior.BottomSheetCallback() {
        override fun onStateChanged(bottomSheet: View, newState: Int) {
            if (newState == BottomSheetBehavior.STATE_HIDDEN) dismiss()
        }

        override fun onSlide(bottomSheet: View, slideOffset: Float) {}
    }

    fun setBottomSheetView(bottomSheetView: BottomSheetInteractor.View) {
        this.mBottomSheetView = bottomSheetView
    }

    @SuppressLint("RestrictedApi")
    override fun setupDialog(dialog: Dialog, style: Int) {
        super.setupDialog(dialog, style)

        _binding = DialogSupportBinding.inflate(layoutInflater)  // Use ViewBinding
        dialog.setContentView(binding.root)

        if (mParams == null) {
            mParams = (binding.root.parent as View).layoutParams as CoordinatorLayout.LayoutParams
        }

        val behavior = mParams!!.behavior
        (binding.root.parent as View).setBackgroundColor(resources.getColor(android.R.color.transparent))
        bottomSheetBehavior = BottomSheetBehavior.from(binding.rootLayout)

        if (behavior is BottomSheetBehavior<*>) {
            bottomSheetBehavior.setBottomSheetCallback(mBottomSheetBehaviorCallback)
        }

        contactService.forEach {
            when (it.type) {
                "telephone" -> {
                    val parts = it.label.split(" or ")
                    binding.ctvCall018.text = parts.getOrNull(1)?.trim() ?: ""
                    binding.ctvCall1800.text = parts[0].trim()
                }

                "website" -> {
                    binding.ctvWebsite.text = it.label
                    website = it.value
                }

                "messenger" -> {
                    binding.txtMessenger.text = it.label
                    messenger = it.value
                }
            }
        }


        // Setup onClickListeners
        binding.ctvCall1800.setOnClickListener(this)
        binding.ctvCall018.setOnClickListener(this)
        binding.ctvWebsite.setOnClickListener(this)
        binding.parentFacebook.setOnClickListener(this)
        binding.parentMessenger.setOnClickListener(this)

        binding.buttonCancel.setOnClickListener {
            bottomSheetBehavior.state = BottomSheetBehavior.STATE_HIDDEN
        }
    }

    @RequiresApi(Build.VERSION_CODES.P)
    override fun onClick(v: View?) {
        if (v == null) return

        when (v.id) {
            R.id.ctv_call018 -> {
                strPhone = binding.ctvCall018.text.toString()
                showCallDialog()
            }

            R.id.ctv_call1800 -> {
                strPhone = binding.ctvCall1800.text.toString()
                showCallDialog()
            }


            R.id.ctv_website -> {
                val intent = Intent(Intent.ACTION_VIEW)
                intent.data = Uri.parse(website)
                startActivity(intent)
            }

            R.id.parent_facebook -> {
                // Handle Facebook click (currently empty)
            }

            R.id.parent_messenger -> {
                try {
                    val intent =
                        Intent(Intent.ACTION_VIEW, Uri.parse("fb-messenger://user/827306730678321"))
                    startActivity(intent)
                } catch (e: Exception) {
                    val intent = Intent(Intent.ACTION_VIEW, Uri.parse("https://m.me/yes kh"))
                    startActivity(intent)
                }
            }
        }
    }

    private fun showCallDialog() {
        if (ContextCompat.checkSelfPermission(
                requireContext(),
                Manifest.permission.CALL_PHONE
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            showCallDialScreenPhone()
        } else {
            requestPermissionLocation()
            ActivityCompat.requestPermissions(
                this as Activity,
                arrayOf(Manifest.permission.CALL_PHONE),
                com.seatel.mobilehall.util.Constant.REQUEST_PHONE_CALL
            )
        }
    }

    private fun showCallDialScreenPhone() {
        val intent = Intent(Intent.ACTION_DIAL)
        intent.data = Uri.parse("tel:$strPhone")
        startActivity(intent)
    }

    private fun requestPermissionLocation() {
        mPhoneNumberRequest = PermissionUtil.with(this)
            .request(Manifest.permission.CALL_PHONE)
            .onAllGranted(object : PermissionUtil.Func() {
                override fun call() {
                    showCallDialScreenPhone()
                }
            }).onAnyDenied(object : PermissionUtil.Func() {
                override fun call() {

                }
            })
            .askPermission(com.seatel.mobilehall.util.Constant.REQUEST_LOCATION_PERMISSION_CODE)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}
