package com.adealink.weparty.wallet.detail.filter

import com.adealink.frame.mvvm.view.viewBinding
import com.adealink.frame.util.onClick
import com.adealink.weparty.commonui.widget.BottomDialogFragment
import com.adealink.weparty.commonui.widget.wheel.WheelDatePickerFragment
import com.adealink.weparty.wallet.R
import com.adealink.weparty.wallet.databinding.DialogWalletDetailFilterBinding

class DetailDateFilterDialog : BottomDialogFragment(R.layout.dialog_wallet_detail_filter) {

    private val binding by viewBinding(DialogWalletDetailFilterBinding::bind)

    private var isEditFromDate = true

    private var listener: OnFilterListener? = null

    private var fromInitTs: Long = 0
    private var fromTs: Long = 0

    private var endInitTs: Long = 0
    private var endTs: Long = 0

    private lateinit var datePickerFragment: WheelDatePickerFragment

    fun setInitTs(fromTs: Long, endTs: Long) {
        this.fromInitTs = fromTs
        this.fromTs = fromTs
        this.endInitTs = endTs
        this.endTs = endTs
    }

    fun setListener(listener: OnFilterListener?) {
        this.listener = listener
    }

    override fun initViews() {
        super.initViews()
        binding.tvFromDate.onClick {
            isEditFromDate = true
            datePickerFragment.getSelectedDate({ timestamp: Long, timeStr: String ->
                this.fromTs = timestamp
            })
            updateUI()
        }
        binding.tvToDate.onClick {
            isEditFromDate = false
            datePickerFragment.getSelectedDate({ timestamp: Long, timeStr: String ->
                this.endTs = timestamp
            })
            updateUI()
        }

        datePickerFragment = WheelDatePickerFragment()
        childFragmentManager.beginTransaction()
            .replace(binding.flDatePicker.id, datePickerFragment, "WheelDatePickerFragment")
            .commitAllowingStateLoss()

        binding.btnConfirm.onClick {
            confirm()
        }
    }

    private fun updateUI() {
        if (isEditFromDate) {
            binding.tvFromDate.isSelected = true
            binding.tvToDate.isSelected = false
        } else {
            binding.tvFromDate.isSelected = false
            binding.tvToDate.isSelected = true
        }
    }

    private fun confirm() {
        if (fromTs != fromInitTs || endTs != endInitTs) {
            listener?.onDateSelected(fromTs, endTs)
        }
        dismiss()
    }

    interface OnFilterListener {
        fun onDateSelected(fromTs: Long, toTs: Long)
    }
}