package com.hanwha.morakmorak.ui.main.home.post

import android.app.AlertDialog
import android.content.Context
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.WindowManager
import android.view.inputmethod.InputMethodManager
import androidx.databinding.DataBindingUtil
import com.google.android.material.snackbar.Snackbar
import com.hanwha.morakmorak.R
import com.hanwha.morakmorak.databinding.ActivityHomePostBinding
import com.hanwha.morakmorak.databinding.DialogHomePostMeetingBinding
import com.hanwha.morakmorak.ui.BindingActivity
import com.hanwha.morakmorak.util.NotNullMutableLiveData
import com.hanwha.morakmorak.util.SoftKeyboard
import com.hanwha.morakmorak.util.ViewUtils
import org.koin.androidx.viewmodel.ext.android.getViewModel
import timber.log.Timber

class HomePostActivity : BindingActivity<ActivityHomePostBinding, HomePostViewModel>() {
    private lateinit var softKeyboard: SoftKeyboard

    override fun getLayoutResId() = R.layout.activity_home_post

    override fun getMyViewModel(): HomePostViewModel = getViewModel()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding.lifecycleOwner = this
        configViewModel()
        setSupportActionBar(binding.toolbar.toolbarPost)
//        configSoftKeyboardListener()
    }

    /**
     * ViewModel Setting
     */
    private fun configViewModel() {
        binding.vm = viewModel.also { viewModel ->

            lateinit var meetingDialog: AlertDialog

            viewModel.toolbarLeftFirstClick = { finish() }

            viewModel.toolbarRightFirstClick = clickRegister@ {
                //                Snackbar.make(
    //                        binding.snackbarCoordinatorLayout,
    //                        "왜 등록해?",
    //                        Snackbar.LENGTH_SHORT).show()
                if (viewModel.body.value.isEmpty() || viewModel.cover.value.isEmpty()
                        || viewModel.dateTime.value.isEmpty() || viewModel.location.value.isEmpty()
                        || viewModel.maxPerson.value.isEmpty() ||  viewModel.title.value.isEmpty()) {

                    Snackbar.make(
                            binding.snackbarCoordinatorLayout,
                            "내용을 모두 입력해주세요.",
                            Snackbar.LENGTH_SHORT).show()
                    return@clickRegister
                }
                viewModel.postParty()
            }

            // 달력 버튼 클릭
            viewModel.onCalendarClick = {
                val dialogBinding = DataBindingUtil.inflate<DialogHomePostMeetingBinding>(
                        layoutInflater,
                        R.layout.dialog_home_post_meeting,
                        null,
                        false).apply { vm = viewModel }

                meetingDialog = AlertDialog.Builder(this@HomePostActivity)
                        .setView(dialogBinding.parentConstraintLayout)
                        .show()
                        .apply { setCanceledOnTouchOutside(false) }

                // Dialog 사이즈 및 배경 투명 설정
                meetingDialog.window?.let {
                    val lp = WindowManager.LayoutParams()
                    lp.copyFrom(it.attributes)
                    lp.width = ViewUtils.dpToPx(270f)
                    lp.height = WindowManager.LayoutParams.WRAP_CONTENT
                    lp.softInputMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE
                    it.attributes = lp
                    it.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
                    it.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)
                }
//                Intent(this@HomePostActivity, PostDialogActivity::class.java)
//                        .apply {
//                            addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION)
//                        }
//                        .run { startActivity(this) }
            }

            // Dialog click listener
            viewModel.onDialogCloseClick = { meetingDialog.dismiss() }
            viewModel.onDialogNegativeClick = {
//                Snackbar.make(binding.snackbarCoordinatorLayout, "왜 취소해?", Snackbar.LENGTH_SHORT).show()
                viewModel.dateTime.clear()
                viewModel.location.clear()
                viewModel.maxPerson.clear()
                viewModel.cover.clear()
                meetingDialog.dismiss()
            }
            viewModel.onDialogPositiveClick = {
                Snackbar.make(binding.snackbarCoordinatorLayout, "저장되었습니다.", Snackbar.LENGTH_SHORT).show()
                meetingDialog.dismiss()
            }

            // 사진 선택 버튼 클릭
            viewModel.onPhotoClick = {
                Snackbar.make(
                        binding.snackbarCoordinatorLayout,
                        "사진을 선택하려면 500만원을 입금해주세요.",
                        Snackbar.LENGTH_SHORT)
                        .show()
            }
            // 카메라 버튼 클릭
            viewModel.onCameraClick = {
                Snackbar.make(
                        binding.snackbarCoordinatorLayout,
                        "사진을 찍으려면 500만원을 입금해주세요.",
                        Snackbar.LENGTH_SHORT)
                        .show()
            }

            viewModel.onCompletePost = {
                if (it) {
                    Snackbar.make(binding.snackbarCoordinatorLayout, "등록을 완료하였습니다.", Snackbar.LENGTH_SHORT).show()
                    finish()
                }
            }
        }
    }

    /**
     * Softkeyboard show/hide listener
     */
    private fun configSoftKeyboardListener() {
        // softkeyboard show/hide listener
        softKeyboard = SoftKeyboard(binding.parentConstraintLayout, getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager).apply {
            setSoftKeyboardCallback(object : SoftKeyboard.SoftKeyboardChanged{
                override fun onSoftKeyboardHide() {
                    Handler(Looper.getMainLooper()).post {
                        Timber.i("onSoftKeyboardHide")
                        binding.vm?.isToolVisibility!!.value = false
                    }
                }

                override fun onSoftKeyboardShow() {
                    Handler(Looper.getMainLooper()).post {
                        Timber.i("onSoftKeyboardShow")
                        binding.vm?.isToolVisibility!!.value = true
                    }
                }

            })
        }
    }

    override fun onDestroy() {
        super.onDestroy()
//        softKeyboard.unRegisterSoftKeyboardCallback()
    }
}

private fun NotNullMutableLiveData<String>.clear() {
    value = ""
}
