package com.example.timert

import android.app.Activity
import android.app.AlertDialog
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.widget.Button
import android.widget.EditText
import android.widget.ImageView
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.ViewModelProvider
import com.example.timert.data.entity.Exercise
import com.example.timert.data.viewModel.ExerciseViewModel

class AllTraining : AppCompatActivity() {
    private var isSave = false
    private lateinit var editExerciseView: EditText
    private lateinit var numExerciseView: EditText
    private lateinit var numRestExerciseView: EditText
    override fun onCreate(savedInstanceState: Bundle?) {
        val exerciseViewModel = ViewModelProvider(
            this,
            ViewModelProvider.AndroidViewModelFactory.getInstance(application)
        )[ExerciseViewModel::class.java]
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_all_training)
        editExerciseView = findViewById(R.id.name_training)
        numExerciseView = findViewById(R.id.time_work)
        numRestExerciseView = findViewById(R.id.rest_workout)

        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        val buttonSaveAll: Button = findViewById(R.id.btn_save_all_vse)
        buttonSaveAll.setOnClickListener {
            val exerciseName = editExerciseView.text.toString()
            val numSetsText = numExerciseView.text.toString()
            val restSetsText = numRestExerciseView.text.toString()

            if (exerciseName.isBlank() || numSetsText.isBlank() || restSetsText.isBlank()) {
                Toast.makeText(this, "Заполните все поля", Toast.LENGTH_SHORT).show()
            } else {
                val numSets = numSetsText.toIntOrNull()
                val restSets = restSetsText.toIntOrNull()

                if (numSets == null || restSets == null) {
                    Toast.makeText(this, "Неверный формат чисел", Toast.LENGTH_SHORT).show()
                    return@setOnClickListener
                }
                val newExercise = Exercise(
                    name_exercise = exerciseName,
                    num_sets = numSets,
                    rest_of_sets = restSets
                )
                exerciseViewModel.insert(newExercise)
                Toast.makeText(this, "Упражнение сохранено", Toast.LENGTH_SHORT).show()
                isSave = true
                finish()
            }




        }


        val button_on_main_all: Button = findViewById(R.id.btn_on_main_all_vse)
        button_on_main_all.setOnClickListener {
            if (isSave == false) {
                AlertDialog.Builder(this)
                    .setTitle("Изменения не сохранены")
                    .setMessage("Продолжить без сохранения?")
                    .setPositiveButton("Да") { _, _ ->

                        val intent = Intent(this, MainActivity::class.java)
                        startActivity(intent)
                        finish()
                    }
                    .setNegativeButton("Нет") { dialog, _ ->
                        dialog.dismiss()
                    }
                    .show()
            } else {
                val intent = Intent(this, MainActivity::class.java)
                startActivity(intent)
            }
        }

        val timeInputRest: EditText = findViewById(R.id.rest_workout)
        val btnPlusTime: ImageView = findViewById(R.id.add_res)
        val btnMinusTime: ImageView = findViewById(R.id.del_res)

        val setsInput: EditText = findViewById(R.id.time_work)
        val btnPlusSets: ImageView = findViewById(R.id.add_set)
        val btnMinusSets: ImageView = findViewById(R.id.del_set)

        setupPlusMinus(timeInputRest, btnPlusTime, btnMinusTime, minValue = 5, maxValue = 600)
        setupPlusMinus(setsInput, btnPlusSets, btnMinusSets, minValue = 5, maxValue = 600)
    }

    companion object {
        const val EXTRA_REPLY = "com.example.android.wordlistsql.REPLY"
    }


    fun setupPlusMinus(
        editText: EditText,
        plus: ImageView,
        minus: ImageView,
        minValue: Int = 5,
        maxValue: Int = 600
    ) {
        plus.setOnClickListener {
            val current = editText.text.toString().toIntOrNull() ?: minValue
            val newValue = (current + 1).coerceAtMost(maxValue)
            editText.setText(newValue.toString())
        }

        minus.setOnClickListener {
            val current = editText.text.toString().toIntOrNull() ?: minValue
            val newValue = (current - 1).coerceAtLeast(minValue)
            editText.setText(newValue.toString())
        }
    }
}