package com.example.timert

import android.content.Intent
import android.os.Bundle
import android.widget.Button
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.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.timert.com.example.timert.data.adapter.WorkoutAdapter
import com.example.timert.data.TrainingItem
import com.example.timert.data.adapter.TrainingAdapter
import com.example.timert.data.viewModel.TrainingViewModel
import com.example.timert.data.viewModel.WorkoutViewModel


class MainActivity : AppCompatActivity() {
    private lateinit var adapter: TrainingAdapter
    private lateinit var workoutViewModel: WorkoutViewModel
    private lateinit var trainingViewModel: TrainingViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)
        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
        }
        adapter = TrainingAdapter(
            onDeleteWorkout = { id -> workoutViewModel.deleteWorkoutById(id) },
            onDeleteTraining = { id -> trainingViewModel.deleteTrainingById(id) },
            onWorkoutClick = { workout ->
                val intent = Intent(this, AddWorkout::class.java)
                intent.putExtra("workout_id", workout.id)
                startActivity(intent)
            },
            onTrainingClick = { training ->
                val intent = Intent(this, CreatingTraining::class.java)
                intent.putExtra("training_id", training.id)
                startActivity(intent)
            }
        )

        val recyclerView = findViewById<RecyclerView>(R.id.workout)
        recyclerView.layoutManager = LinearLayoutManager(this)
        recyclerView.adapter = adapter

        workoutViewModel = ViewModelProvider(this)[WorkoutViewModel::class.java]
        trainingViewModel = ViewModelProvider(this)[TrainingViewModel::class.java]

        // объединяем данные вручную
        val combinedList = mutableListOf<TrainingItem>()

        workoutViewModel.allWorkouts.observe(this) { workouts ->
            combinedList.clear()
            combinedList.addAll(workouts.map { TrainingItem.WorkoutItem(it) })

            trainingViewModel.allTrainingsWithExercises.value?.let { trainings ->
                combinedList.addAll(trainings.map { TrainingItem.TrainingWithExercisesItem(it) })
            }

            adapter.submitList(combinedList.toList())
        }

        trainingViewModel.allTrainingsWithExercises.observe(this) { trainings ->
            combinedList.clear()
            workoutViewModel.allWorkouts.value?.let { workouts ->
                combinedList.addAll(workouts.map { TrainingItem.WorkoutItem(it) })
            }
            combinedList.addAll(trainings.map {TrainingItem.TrainingWithExercisesItem(it) })
            adapter.submitList(combinedList.toList())
        }





        // Кнопки главной формы:
        val settingsButton: Button = findViewById(R.id.settingsButton)
        settingsButton.setOnClickListener {
            val intent = Intent(this, SettingsActivity::class.java)
            startActivity(intent)
        }

        val startTrainingButton: Button = findViewById(R.id.startTrainingButton)
        startTrainingButton.setOnClickListener {
            Toast.makeText(this, "Запуск тренировки!", Toast.LENGTH_SHORT).show() // Заглушка
            //TODO: Intent для запуска Activity тренировки (форма 5)
            val intent = Intent(this, timer::class.java)
            startActivity(intent)
        }

        val templatesButton: Button = findViewById(R.id.templatesButton)
        templatesButton.setOnClickListener {
            //Toast.makeText(this, "Открытие шаблонов!", Toast.LENGTH_SHORT).show() // Заглушка
            //TODO: Intent для открытия Activity шаблонов (форма 3)
            val intent = Intent(this, AddWorkout::class.java)
            startActivity(intent)
        }

        val newTemplateButton: Button = findViewById(R.id.newTemplateButton)
        newTemplateButton.setOnClickListener {
            //Toast.makeText(this, "Создание нового шаблона!", Toast.LENGTH_SHORT).show() // Заглушка
            //TODO: Intent для открытия Activity создания шаблона (форма 7)
            val intent = Intent(this, History::class.java)
            startActivity(intent)
        }

        //  ----  ROOM TEST  ----
    }
}