package com.bravelocation.yeltzlandnew.views

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material.*
import androidx.compose.material.MaterialTheme.colors
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.outlined.Refresh
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextOverflow
import androidx.navigation.NavController
import com.bravelocation.yeltzlandnew.models.LeagueTable
import com.bravelocation.yeltzlandnew.models.LoadingState
import com.bravelocation.yeltzlandnew.ui.YeltzlandTheme
import com.bravelocation.yeltzlandnew.viewmodels.LeagueTableViewModel
import com.google.accompanist.swiperefresh.SwipeRefresh
import com.google.accompanist.swiperefresh.rememberSwipeRefreshState

@Composable
fun LeagueTableActivityView(
    model: LeagueTableViewModel,
    navController: NavController
) {
    val table: LeagueTable? by model.table.collectAsState()
    val loadingState: LoadingState by model.loadingState.observeAsState(LoadingState.LOADING)

    val swipeRefreshState = rememberSwipeRefreshState(false)

    YeltzlandTheme {
        Scaffold(topBar = {
            TopAppBar(
                title = {
                    Text(text = "League Table", maxLines = 1, overflow = TextOverflow.Ellipsis)
                },
                navigationIcon = {
                    IconButton(onClick = {
                        navController.popBackStack()
                    }) {
                        Icon(Icons.Filled.ArrowBack,"Back", tint = colors.onPrimary)
                    }
                },
                actions = {
                    IconButton(onClick = {
                        model.load()
                    }) {
                        Icon(Icons.Outlined.Refresh,"Reload", tint = colors.onPrimary)
                    }
                },
                backgroundColor = colors.primary,
                contentColor = colors.onPrimary
            )
        }) { padding ->
            SwipeRefresh(
                state = swipeRefreshState,
                onRefresh = { model.load() }
            ) {
                Box(modifier = Modifier
                    .fillMaxSize()
                    .background(colors.background)
                    .padding(padding)
                ) {
                    table?.let { it1 -> LeagueTableView(it1) }
                    LoadingOverlay(loadingState == LoadingState.LOADING)
                    ErrorMessageOverlay(isDisplayed = loadingState == LoadingState.ERROR)
                }
            }
        }
    }
}