package com.mytatvarnsdk.activity

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.widget.AppCompatImageView
import androidx.constraintlayout.widget.ConstraintLayout
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import com.mytatvarnsdk.R

class ExitJourneyBottomSheet : BottomSheetDialogFragment() {
    private var exitListener: OnExitListener? = null

    fun interface OnExitListener {
        fun onExitConfirmed()
    }

    fun setOnExitListener(listener: OnExitListener?) {
        this.exitListener = listener
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setStyle(STYLE_NORMAL, R.style.CustomBottomSheetDialogTheme)
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.exit_dialog_bottomsheet, container, false)
    }

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

        val exitButton = view.findViewById<ConstraintLayout>(R.id.btnExit)
        val cancelButton = view.findViewById<ConstraintLayout>(R.id.btnCancel)
        val closeButton = view.findViewById<AppCompatImageView>(R.id.close_button)

        exitButton.setOnClickListener(View.OnClickListener { v: View? ->
            if (exitListener != null) {
                exitListener!!.onExitConfirmed()
            }
            dismiss()
        })

        cancelButton.setOnClickListener(View.OnClickListener { v: View? -> dismiss() })
        closeButton.setOnClickListener(View.OnClickListener { v: View? -> dismiss() })
    }

    override fun onStart() {
        super.onStart()
        if (getDialog() != null) {
            val bottomSheet =
                getDialog()!!.findViewById<View?>(com.google.android.material.R.id.design_bottom_sheet)
            if (bottomSheet != null) {
                // Force the bottom sheet to expand fully
                val behavior =
                    BottomSheetBehavior.from<View?>(bottomSheet)
                behavior.setState(BottomSheetBehavior.STATE_EXPANDED)
                behavior.setSkipCollapsed(true)
                behavior.setHideable(true)

                // Set height to match parent
                bottomSheet.getLayoutParams().height = ViewGroup.LayoutParams.WRAP_CONTENT
            }
        }
    }

    companion object {
        fun newInstance(): ExitJourneyBottomSheet {
            return ExitJourneyBottomSheet()
        }
    }
}
