package com.example.smartlab

import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.os.Build
import android.os.Bundle
import android.os.CountDownTimer
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.View
import android.view.WindowManager
import android.widget.TextView
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import com.example.smartlab.Model.APIUse
import com.example.smartlab.Model.ApiData
import com.example.smartlab.databinding.ActivityEmailCodeBinding
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.awaitResponse


class EmailCodeActivity : AppCompatActivity() {

    lateinit var binding: ActivityEmailCodeBinding
    private lateinit var counter: TextView
    private lateinit var num1: TextView
    private lateinit var num2: TextView
    private lateinit var num3: TextView
    private lateinit var num4: TextView
    private var code: String = ""
    private var flag: Boolean = true
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityEmailCodeBinding.inflate(layoutInflater)
        setContentView(binding.root)

        counter = binding.sekondCounter
        num1 = binding.editNum1
        num2 = binding.editNum2
        num3 = binding.editNum3
        num4 = binding.editNum4

        init()
    }

    private fun init() {
        listenerCode()
        openSoftKeyboard(this, num1)
        counterText()
    }

    private fun listenerCode() {
        binding.editNum1.addTextChangedListener(object : TextWatcher {
            @RequiresApi(Build.VERSION_CODES.M)
            override fun afterTextChanged(s: Editable) {
            }

            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
                if (s.length != 0) {
                    code += s;
                    binding.editNum2.requestFocus();
                }
                if (s.length == 0) {
                    code = ""
                }
            }

        })
        binding.editNum2.addTextChangedListener(object : TextWatcher {
            @RequiresApi(Build.VERSION_CODES.M)
            override fun afterTextChanged(s: Editable) {
            }

            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
                if (s.length != 0)
                {code += s;
                    binding.editNum3.requestFocus();}

                if (s.length == 0) {
                    binding.editNum1.requestFocus();
                    code = code.substring(0, 1)
                }
            }
        })
        binding.editNum3.addTextChangedListener(object : TextWatcher {
            @RequiresApi(Build.VERSION_CODES.M)
            override fun afterTextChanged(s: Editable) {
            }

            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
                if (s.length != 0) {
                    code += s;
                    binding.editNum4.requestFocus();
                }
                if (s.length == 0) {
                    binding.editNum2.requestFocus();
                    code = code.substring(0, 2)
                }
            }
        })
        binding.editNum4.addTextChangedListener(object : TextWatcher {
            @RequiresApi(Build.VERSION_CODES.M)
            override fun afterTextChanged(s: Editable) {
            }

            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
                if (s.length != 0) {
                    code += s;
                    if (code.length == 4) {
                        check()
                    }
                }
                if (s.length == 0) {
                    binding.editNum3.requestFocus();
                    code = code.substring(0, 3)
                }
            }
        })
    }

    private fun check() {
        val intent: Intent = Intent(this@EmailCodeActivity, CreatePasswordActivity::class.java)
        APIUse.apiService.SignIn(ApiData.email, code).enqueue(object : Callback<String> {
            override fun onResponse(call: Call<String>, response: Response<String>) {
                if (response.code() == 200) {
                    if (response.body() != null) {
                        flag = false
                        startActivity(intent)
                    }
                }
            }

            override fun onFailure(call: Call<String>, t: Throwable) {
                Toast.makeText(
                    this@EmailCodeActivity,
                    "Что-то пошло не так",
                    Toast.LENGTH_SHORT
                ).show()
            }
        })
    }

    private fun openSoftKeyboard(context: Context, view: View) {
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE)
        binding.editNum1.requestFocus()
    }

    private fun counterText() {
        val str1: String = "Отправить код повторно можно будет через "
        val str2: String = " секунд"

        object : CountDownTimer(60000, 1000) {

            // Callback function, fired on regular interval
            override fun onTick(millisUntilFinished: Long) {
                counter.setText(str1 + millisUntilFinished / 1000 + str2)
            }

            override fun onFinish() {
            }
        }.start()
    }

    fun onClickBackEmail() {
        finish()
    }

    override fun onSaveInstanceState(savedInstanceState: Bundle) {
        super.onSaveInstanceState(savedInstanceState)
        val editor: SharedPreferences.Editor =
            getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit()
        editor.putBoolean("AuthorizationFlag", flag).commit()
        editor.apply()
    }
}