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.ImageButton
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 androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.timert.data.adapter.ExerciseAdapter
import com.example.timert.data.entity.Training
import com.example.timert.data.viewModel.ExerciseViewModel
import com.example.timert.data.viewModel.TrainingViewModel
import com.example.timert.data.viewModel.WorkoutViewModel
import kotlinx.coroutines.launch

class CreatingTraining : AppCompatActivity() {

    private lateinit var viewModel: ExerciseViewModel
    private lateinit var trainingViewModel: TrainingViewModel

    private lateinit var name_training: EditText
    private lateinit var numSets: EditText
    private lateinit var restSets: EditText

    private var isSave = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_creating_training)
        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
        }
        name_training = findViewById(R.id.name_training)
        numSets = findViewById(R.id.numbers_of_sets)
        restSets = findViewById(R.id.rest_sets)


        val recyclerView = findViewById<RecyclerView>(R.id.exercise)
        val buttonSave: Button = findViewById(R.id.btn_save)

        viewModel = ViewModelProvider(this)[ExerciseViewModel::class.java]
        trainingViewModel = ViewModelProvider(this)[TrainingViewModel::class.java]

        val adapter = ExerciseAdapter { id ->
            viewModel.deleteExerciseById(id)
        }


        recyclerView.adapter = adapter
        recyclerView.layoutManager = LinearLayoutManager(this)
        val type = intent.getStringExtra("type")
        val trainingId = intent.getIntExtra("trainingId", -1)
        if (trainingId != -1) {
            // Загружаем тренировку по ID
            trainingViewModel.getTrainingById(trainingId).observe(this) { training ->
                name_training.setText(training.name)
                numSets.setText(training.numSets.toString())
                restSets.setText(training.restBetweenSets.toString())
            }

            if (type == "trainingWithExercises") {
                // Загружаем упражнения только если тренировка с упражнениями
                viewModel.getExercisesByTrainingId(trainingId).observe(this) { exercises ->
                    adapter.setExercises(exercises)
                }
                viewModel.unsavedExercises.observe(this) { exercises ->
                    adapter.setExercises(exercises)
                }
            } else {
                adapter.setExercises(emptyList()) // у обычной тренировки нет упражнений
            }
        } else {
            // Создание новой — поля пустые, список упражнений пустой
            adapter.setExercises(emptyList())
        }



        buttonSave.setOnClickListener {
            val name = name_training.text.toString()
            val numS = numSets.text.toString()
            val resS = restSets.text.toString()

            if (name.isBlank() || numS.isBlank() || resS.isBlank()) {
                Toast.makeText(this, "Заполните все поля", Toast.LENGTH_SHORT).show()
            } else {

                val sets = numS.toIntOrNull()
                val rest = resS.toIntOrNull()

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

                val newTraining = Training(
                    name = name,
                    numSets = sets,
                    restBetweenSets = rest)

                trainingViewModel.insertTrainingAndLinkExercises(newTraining)

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


                isSave = true
            }

        }

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


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

        setupPlusMinus(restSets, btnPlusTime, btnMinusTime, minValue = 5, maxValue = 600)
        setupPlusMinus(numSets, btnPlusSets, btnMinusSets, minValue = 1, maxValue = 20)
        val button_on_main: Button = findViewById(R.id.btn_on_main)
        button_on_main.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_workout)
        button_add.setOnClickListener {
            val intent = Intent(this, AllTraining::class.java)
            startActivity(intent)
        }

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