package com.example.timert

import android.app.AlertDialog
import android.content.Intent
import android.media.MediaPlayer
import android.os.Bundle
import android.os.CountDownTimer
import android.widget.ImageButton
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat

class timer : AppCompatActivity() {
    private var isPlay = false

    private lateinit var statusText: TextView
    private lateinit var timerText: TextView
    private lateinit var statusSet: TextView
    private lateinit var statusExercise: TextView
    private var numApproaches = 3
    private var numExercises = 5
    private var restBetweenExercises = 30
    private var restBetweenApproaches = 60
    private var exerciseDuration = 45  // например, 45 секунд упражнение
    private var currentTimer: CountDownTimer? = null
    private var timeLeftInMillis: Long = 0

    // Объявляем переменные для MediaPlayer
    private var startWorkoutSound: MediaPlayer? = null
    private var workSound: MediaPlayer? = null
    private var startRestSound: MediaPlayer? = null
    private var restSound: MediaPlayer? = null


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_timer)
        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
        }
        statusText = findViewById(R.id.statusText)
        timerText = findViewById(R.id.timerText)
        statusSet = findViewById(R.id.number_set)
        statusExercise = findViewById(R.id.num_exercise)
        numApproaches = intent.getIntExtra("numApproaches", numApproaches)
        numExercises = intent.getIntExtra("numExercises", numExercises)
        restBetweenExercises = intent.getIntExtra("restBetweenExercises", restBetweenExercises)
        restBetweenApproaches = intent.getIntExtra("restBetweenApproaches", restBetweenApproaches)
        exerciseDuration = intent.getIntExtra("exerciseDuration", exerciseDuration)

        // Инициализируем MediaPlayer
        startWorkoutSound = MediaPlayer.create(this, R.raw.sound1)
        workSound = MediaPlayer.create(this, R.raw.sound1)
        startRestSound = MediaPlayer.create(this, R.raw.sound2)
        restSound = MediaPlayer.create(this, R.raw.sound3)

        startTraining()

        val button: ImageButton = findViewById(R.id.stop)
        button.setOnClickListener {
            AlertDialog.Builder(this)
                .setTitle("Сброс таймера")
                .setMessage("Закрыть таймер и перейти на главную страницу?")
                .setPositiveButton("Да") { _, _ ->

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



        val pauseButton: ImageButton = findViewById(R.id.play)

        pauseButton.setOnClickListener {
            if (isPlay) {

                pauseButton.setImageResource(R.drawable.icon_play)
                // здесь ещё можно возобновить таймер
            } else {

                pauseButton.setImageResource(R.drawable.icon_pause)
                // здесь можно остановить таймер
            }
            isPlay = !isPlay
        }



    }
    private fun resumeTimer(onFinish: () -> Unit) {
        currentTimer = object : CountDownTimer(timeLeftInMillis, 1000) {
            override fun onTick(millisUntilFinished: Long) {
                timeLeftInMillis = millisUntilFinished
                timerText.text = "${millisUntilFinished / 1000}"
            }

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

    private fun startTraining() {
        var currentApproach = 1
        val rootLayout = findViewById<ConstraintLayout>(R.id.main)
        fun nextApproach() {
            if (currentApproach > numApproaches) {
                statusText.text = "Тренировка завершена!"
                rootLayout.setBackgroundResource(R.drawable.blue_gradient)
                timerText.text = "00:00"
                // Здесь должен быть звук завершения тренировки, если нужно
                return
            }
            statusSet.text = "Подход № $currentApproach"
            var currentExercise = 1

            fun nextExercise() {
                if (currentExercise > numExercises) {
                    statusText.text = "Отдых между подходами"
                    rootLayout.setBackgroundResource(R.drawable.green_gradient)
                    // Звук перед началом отдыха между подходами
                    startRestSound?.start()
                    startRest(restBetweenApproaches) {
                        currentApproach++
                        nextApproach()
                    }
                    return
                }
                rootLayout.setBackgroundResource(R.drawable.gradient_pink)
                statusText.text = "Работа"
                statusExercise.text = "$currentExercise / $numExercises"
                statusSet.text = "$currentApproach"

                // Звук перед началом упражнения
                workSound?.start()

                startTimer(exerciseDuration) {
                    statusText.text = "Отдых"
                    rootLayout.setBackgroundResource(R.drawable.green_gradient)
                    // Звук перед началом отдыха между упражнениями
                    restSound?.start()
                    startRest(restBetweenExercises) {
                        currentExercise++
                        nextExercise()
                    }
                }
            }
            // Звук перед началом подхода
            startWorkoutSound?.start()
            nextExercise()
        }
        nextApproach()
    }

    private fun startTimer(seconds: Int, onFinish: () -> Unit) {
        timeLeftInMillis = seconds * 1000L
        object : CountDownTimer(seconds * 1000L, 1000) {
            override fun onTick(millisUntilFinished: Long) {
                timerText.text = "${millisUntilFinished / 1000}"
            }

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

    private fun startRest(seconds: Int, onFinish: () -> Unit) {
        val rootLayout = findViewById<ConstraintLayout>(R.id.main)
        rootLayout.setBackgroundResource(R.drawable.green_gradient)
        object : CountDownTimer(seconds * 1000L, 1000) {
            override fun onTick(millisUntilFinished: Long) {
                timerText.text = "${millisUntilFinished / 1000}"
                statusText.text = "Отдых"
            }

            override fun onFinish() {
                onFinish()
            }
        }.start()
    }
    override fun onDestroy() {
        super.onDestroy()
        currentTimer?.cancel()
        // Освобождаем ресурсы MediaPlayer
        startWorkoutSound?.release()
        workSound?.release()
        startRestSound?.release()
        restSound?.release()

        startWorkoutSound = null
        workSound = null
        startRestSound = null
        restSound = null
    }
}