package com.example.timert

import android.app.AlertDialog
import android.content.Intent
import android.os.Bundle
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.com.example.timert.data.entity.Workout
import com.example.timert.data.viewModel.WorkoutViewModel


class AddWorkout : AppCompatActivity() {
    private var isSave = false
    private lateinit var editWorkoutView: EditText
    private lateinit var numWorkoutView: EditText
    private lateinit var numRestWorkoutView: EditText
    private lateinit var numRestSetsView: EditText
    private lateinit var numSetsView: EditText
    private lateinit var timeWorkoutView: EditText

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_add_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 workoutViewModel = ViewModelProvider(
            this,
            ViewModelProvider.AndroidViewModelFactory.getInstance(application)
        )[WorkoutViewModel::class.java]
        val workoutId = intent.getIntExtra("workoutId", -1)



        editWorkoutView = findViewById(R.id.name_training)
        numWorkoutView = findViewById(R.id.num_exercise)
        numRestWorkoutView = findViewById(R.id.rest_workout_all)
        numRestSetsView = findViewById(R.id.rest_sets_all)
        numSetsView = findViewById(R.id.numbers_of_sets_all)
        timeWorkoutView = findViewById(R.id.time_work_all)

        if (workoutId != -1) {
            val viewModel = ViewModelProvider(
                this,
                ViewModelProvider.AndroidViewModelFactory.getInstance(application)
            )[WorkoutViewModel::class.java]

            viewModel.allWorkouts.observe(this) { workouts ->
                val workout = workouts.find { it.id == workoutId }
                if (workout != null) {
                    editWorkoutView.setText(workout.name)
                    numWorkoutView.setText(workout.numExercises.toString())
                    numRestWorkoutView.setText(workout.restBetweenExercises.toString())
                    numRestSetsView.setText(workout.restBetweenApproaches.toString())
                    numSetsView.setText(workout.numApproaches.toString())
                    timeWorkoutView.setText(workout.exerciseDuration.toString())
                }
                }


                }


        val buttonSaveAll: Button = findViewById(R.id.btn_save_all)
        buttonSaveAll.setOnClickListener {

            val workoutName = editWorkoutView.text.toString()
            val numWorkoutText = numWorkoutView.text.toString()
            val restWorkoutText = numRestWorkoutView.text.toString()
            val restSetsText = numRestSetsView.text.toString()
            val numSetsText = numSetsView.text.toString()
            val timeWorkText =  timeWorkoutView.text.toString()



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

                if (numSets == null || restSets == null || numExercise == null || restExercise == null || timeWorkExercise == null) {
                    Toast.makeText(this, "Неверный формат чисел", Toast.LENGTH_SHORT).show()
                    return@setOnClickListener
                }

                val newWorkout = Workout(
                    name = workoutName,
                    numApproaches = numSets,
                    numExercises = numExercise,
                    restBetweenExercises = restExercise,
                    restBetweenApproaches = restSets,
                    exerciseDuration = timeWorkExercise,
                )
                workoutViewModel.insert(newWorkout)

                Toast.makeText(this, "Тренировка сохранена", Toast.LENGTH_SHORT).show()

                isSave = true

            }

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

                        val intent = Intent(this, MainActivity::class.java)
                        startActivity(intent)
                    }
                    .setNegativeButton("Нет") { dialog, _ ->
                        dialog.dismiss()
                    }
                    .show()
            } else {
                val intent = Intent(this, MainActivity::class.java)
                startActivity(intent)
            }
        }
        val button_add: Button = findViewById(R.id.add_workoutadd)
        button_add.setOnClickListener {
            val intent = Intent(this, CreatingTraining::class.java)
            startActivity(intent)
        }
        val timeInputRestSetAll: EditText = findViewById(R.id.rest_sets_all)
        val btnPlusTimeAll: ImageView = findViewById(R.id.add_res_set2)
        val btnMinusTimeAll: ImageView = findViewById(R.id.del_res_set2)

        val setsInputAll: EditText = findViewById(R.id.numbers_of_sets_all)
        val btnPlusSetsAll: ImageView = findViewById(R.id.add_set3)
        val btnMinusSetsAll: ImageView = findViewById(R.id.del_set3)

        val timeInputRest: EditText = findViewById(R.id.rest_workout_all)
        val btnPlusTimeWor: ImageView = findViewById(R.id.add_res)
        val btnMinusTimeWor: ImageView = findViewById(R.id.del_res)

        val timeWork: EditText = findViewById(R.id.time_work_all)
        val Plus: ImageView = findViewById(R.id.add_set)
        val Minus: ImageView = findViewById(R.id.del_set)

        val numExer: EditText = findViewById(R.id.num_exercise)
        val PlusExer: ImageView = findViewById(R.id.add_set4)
        val MinusExer: ImageView = findViewById(R.id.del_set4)


        setupPlusMinus(timeInputRestSetAll, btnPlusTimeAll, btnMinusTimeAll, minValue = 5, maxValue = 600)
        setupPlusMinus(setsInputAll, btnPlusSetsAll, btnMinusSetsAll, minValue = 1, maxValue = 20)
        setupPlusMinus(timeInputRest, btnPlusTimeWor, btnMinusTimeWor, minValue = 5, maxValue = 600)
        setupPlusMinus(timeWork, Plus, Minus, minValue = 5, maxValue = 600)
        setupPlusMinus(numExer, PlusExer, MinusExer, minValue = 1, maxValue = 50)


    }
    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())
        }
    }
}