package kr.co.vividnext.sodalive.main

import android.app.Dialog
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import coil.load
import coil.transform.RoundedCornersTransformation
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import kr.co.vividnext.sodalive.R
import kr.co.vividnext.sodalive.common.SharedPreferenceManager
import kr.co.vividnext.sodalive.extensions.dpToPx
import kr.co.vividnext.sodalive.settings.event.EventItem

class EventPopupDialogFragment(
    private val screenWidth: Int,
    private val eventItem: EventItem,
    private val onClick: () -> Unit
) : BottomSheetDialogFragment() {

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val dialog = super.onCreateDialog(savedInstanceState)

        dialog.setOnShowListener {
            val d = it as BottomSheetDialog
            val bottomSheet = d.findViewById<FrameLayout>(
                com.google.android.material.R.id.design_bottom_sheet
            )
            if (bottomSheet != null) {
                BottomSheetBehavior.from(bottomSheet).state = BottomSheetBehavior.STATE_EXPANDED
            }
        }

        return dialog
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View = inflater.inflate(R.layout.fragment_event_popup_dialog, container, false)

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        view.findViewById<TextView>(R.id.tv_close).setOnClickListener {
            dialog?.dismiss()
        }

        view.findViewById<TextView>(R.id.tv_close_always).setOnClickListener {
            SharedPreferenceManager.notShowingEventPopupId = eventItem.id
            dialog?.dismiss()
        }

        val imageView = view.findViewById<ImageView>(R.id.iv_event_popup)
        val layoutParams = imageView.layoutParams as LinearLayout.LayoutParams

        layoutParams.width = screenWidth
        layoutParams.height = screenWidth

        imageView.load(eventItem.popupImageUrl) {
            crossfade(true)
            transformations(
                RoundedCornersTransformation(
                    topLeft = 16.7f.dpToPx(),
                    topRight = 16.7f.dpToPx(),
                    bottomLeft = 0f,
                    bottomRight = 0f
                )
            )
        }
        imageView.layoutParams = layoutParams

        imageView.setOnClickListener {
            dialog?.dismiss()
            onClick()
        }
    }
}
