package com.epfl.esl.sportstracker

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.compose.LifecycleEventEffect
import androidx.lifecycle.viewmodel.compose.viewModel
import com.epfl.esl.sportstracker.ui.theme.SportsTrackerTheme

@Composable
fun MyHistoryScreen(
    username: String,
    modifier: Modifier = Modifier,
    myHistoryViewModel: MyHistoryViewModel = viewModel()
) {
    Surface(
        modifier = modifier.fillMaxSize(),
        color = MaterialTheme.colorScheme.background
    ) {
        val sessions by myHistoryViewModel.sessions.observeAsState()
        LifecycleEventEffect(event = Lifecycle.Event.ON_RESUME) {
            myHistoryViewModel.listenForHistory(username)
        }
        sessions?.let {
            LazyColumn {
                items(it) { session ->
                    SessionItemRow(sessionItem = session, Modifier.padding(8.dp))
                }
            }
        }
    }
}

@Preview
@Composable
fun MyHistoryScreenPreview() {
    SportsTrackerTheme {
        MyHistoryScreen("")
    }
}
