package io.nexilis.alpha.ui.main

import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import coil.compose.AsyncImage
import coil.request.ImageRequest
import io.nexilis.alpha.R
import io.nexilis.alpha.ui.viewmodel.MainViewModel
import io.nexilis.service.data.viewmodels.BuddyViewModel

@OptIn(ExperimentalFoundationApi::class)
@Composable
fun Home(
    contentPadding: PaddingValues = PaddingValues(0.dp),
    mainViewModel: MainViewModel
) {
    SideEffect {
        mainViewModel.setTitle("Home")
    }
    val viewModel: BuddyViewModel = hiltViewModel()
    val all by viewModel.all.observeAsState()
    LazyVerticalGrid(
        columns = GridCells.Fixed(3),
        contentPadding = contentPadding,
        horizontalArrangement = Arrangement.spacedBy(2.dp),
        verticalArrangement = Arrangement.spacedBy(2.dp),
        modifier = Modifier
            .fillMaxWidth()
            .fillMaxHeight()
    ) {
        items(
            count = all?.size ?: 0,
            key = {
                all?.get(it)?.f_pin ?: 0
            }
        ) { item ->
            val buddy = all?.get(item)
            val mod = Modifier
                .animateItemPlacement()
                .aspectRatio(1f)
                .fillMaxWidth()
            AsyncImage(
                model = ImageRequest.Builder(LocalContext.current)
                    .data("https://digixplatform.com/filepalio/image/${buddy?.image_id}")
                    .addHeader("Cookie" , "PHPSESSID=123;MOBILE=123")
                    .crossfade(true)
                    .build(),
                placeholder = painterResource(R.drawable.ic_placeholder),
                contentDescription = "",
                contentScale = ContentScale.Crop,
                modifier = mod
            )
        }
    }
}