package ta1.cis.activity

import android.annotation.SuppressLint
import android.app.TimePickerDialog
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.format.DateFormat
import android.util.Log
import android.view.View
import android.widget.TimePicker
import android.widget.Toast
import androidx.annotation.RequiresApi
import com.google.android.material.datepicker.CalendarConstraints
import com.google.android.material.datepicker.DateValidatorPointForward
import com.google.android.material.datepicker.MaterialDatePicker
import kotlinx.android.synthetic.main.activity_edit_izin_bermalam.*
import kotlinx.android.synthetic.main.activity_request_izin_bermalam.*
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import ta1.cis.R
import ta1.cis.api.RetrofitInstance
import ta1.cis.helper.SharedPref
import ta1.cis.model.request.IBRequest
import ta1.cis.model.response.Data
import ta1.cis.model.response.DataIzin
import java.text.SimpleDateFormat
import java.time.LocalDateTime
import java.time.ZoneId
import java.time.format.DateTimeFormatter
import java.util.*

class EditIzinBermalam : AppCompatActivity() {

    private lateinit var sharedPref: SharedPref;

    private var waktuBerangkat : String = ""
    private lateinit var dataIzinIntent : DataIzin;
    private var waktuKembali : String = ""
    companion object{
        val dataIzin = "DATA_IZIN"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_edit_izin_bermalam)
        dataIzinIntent = intent.getParcelableExtra<DataIzin>(dataIzin) as DataIzin
        sharedPref = SharedPref(this)
        var millis = 0L
        btn_berangkat_edit.setOnClickListener {
//                millis = getTimeInMillis(btn_berangkat_edit.text.toString())
//            Log.d("Millis", millis.toString())
            getDate(0)
        }
        btn_edit.setOnClickListener {
            getDate(1)
        }
        bindData(dataIzinIntent)
        editBtn.setOnClickListener {
            var data = IBRequest(
                tgl_berangkat_edit.text.toString(),
                tgl_kembali_edit.text.toString(),
                keperluanIbEdit.text.toString(),
                tujuanEdit.text.toString()
            )
            editData(data)
        }
    }

    private fun getDate(id : Int) {
        val mcurrentDate: Calendar = Calendar.getInstance()
        val mYear: Int = mcurrentDate.get(Calendar.YEAR)
        val mMonth: Int = mcurrentDate.get(Calendar.MONTH)
        val mDay: Int = mcurrentDate.get(Calendar.DAY_OF_MONTH)
        mcurrentDate.add(Calendar.DATE, 1);
        val constraintBuilder = CalendarConstraints.Builder().setValidator(DateValidatorPointForward.from(mcurrentDate.timeInMillis))
        val picker = MaterialDatePicker.Builder
            .datePicker()
            .setTitleText("Pilih Waktu Berangkat")
            .setSelection(mcurrentDate.timeInMillis)
            .setCalendarConstraints(constraintBuilder.build())
            .build()

        picker.show(supportFragmentManager,"tag")
        picker.addOnPositiveButtonClickListener { selection: Long ->

            val timeZoneUTC = TimeZone.getDefault()
            val offsetFromUTC = timeZoneUTC.getOffset(Date().time) * -1
            val simpleFormat = SimpleDateFormat("yyyy-MM-dd", Locale.US)
            val date = Date(selection + offsetFromUTC)
            val mcurrentDate: Calendar = Calendar.getInstance()
//            var waktuBerangkat :String = simpleFormat.format(date)
            if(id == 0){
                waktuBerangkat = simpleFormat.format(date)
            }else{
                waktuKembali = simpleFormat.format(date)
            }
            val timePicker = TimePickerDialog(this,
                { view, hourOfDay, minute ->
                    if (id == 0) {
                        waktuBerangkat += " ${hourOfDay}:${minute}:00"
                        tgl_berangkat_edit.setText(waktuBerangkat.toString())
                    } else {
                        waktuKembali += " ${hourOfDay}:${minute}:00"
                        tgl_kembali_edit.setText(waktuKembali.toString())
                    }
                },mcurrentDate.get(Calendar.HOUR_OF_DAY), mcurrentDate.get(Calendar.MINUTE), DateFormat.is24HourFormat(this))
            timePicker.show()
        }
    }

    private fun getTimeInMillis(date: String): Long{
        var sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
        var date = sdf.parse(date)
        var millis = date.time
        return millis

    }
    fun bindData(data: DataIzin){
        var tglBerangkat = intent.getStringExtra("tglBerangkat")
        tgl_berangkat_edit.setText(tglBerangkat)
        var tglKembali = intent.getStringExtra("tglKembali")
        tgl_kembali_edit.setText(tglKembali)
        keperluanIbEdit.setText(data.keperluanIb)
        tujuanEdit.setText(data.tujuan)
    }

    fun editData(data: IBRequest){
        pb_ibEdit.visibility = View.VISIBLE
        RetrofitInstance.instanceRetrofit.editIzinBermalam(dataIzinIntent.idIzin!!.toLong(),sharedPref.getDimId().toLong(),data,"Bearer ${sharedPref.getTokenBearer()}")
            .enqueue(object : Callback<Unit>{
                override fun onResponse(call: Call<Unit>, response: Response<Unit>) {
                    Toast.makeText(this@EditIzinBermalam,"Data Berhasil di update",Toast.LENGTH_LONG).show()
                    sharedPref.setStatusUpdate(2)
                    pb_ibEdit.visibility = View.GONE
                    onBackPressed()
                }

                override fun onFailure(call: Call<Unit>, t: Throwable) {

                    pb_ibEdit.visibility = View.GONE
                    Toast.makeText(this@EditIzinBermalam,"Ada Masalah pada Internet",Toast.LENGTH_LONG).show()
                }
            }
        )
    }
}