package de.jadehs.strassenschadenpro2.pages

import android.util.Log
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.Divider
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import de.jadehs.strassenschadenpro2.Feature
import de.jadehs.strassenschadenpro2.ListViewModel

@Composable
fun ListPage(modifier: Modifier = Modifier, listViewModel: ListViewModel, onFeatureClick: (Int) -> Unit) {
    val features = listViewModel.features.collectAsState()
    LaunchedEffect(Unit) {
        listViewModel.fetch()
        Log.d("test",""+features.value.size)
    }

    LazyColumn(modifier = modifier) {
        items(features.value){ feature ->
            FeatureItem(feature = feature,
                onClick = {
                    feature.properties?.OBJECTID?.let { objectId ->
                        onFeatureClick(objectId)
                    }
                }
            )
        }
    }
}

@Composable
fun FeatureItem(feature: Feature, onClick: () -> Unit){
    Column(modifier = Modifier
        .fillMaxWidth()
        .clickable {onClick()}
        .padding(12.dp)
    ) {
        Text(
            text = "Typ: ${feature.properties?.Typ ?: "-"}",
            style = MaterialTheme.typography.titleMedium
        )
        Text(
            text = "Beschreibung: ${feature.properties?.Beschreibung ?: "-"}",
            style = MaterialTheme.typography.bodyMedium
        )

        val coords = feature.geometry?.coordinates
        val coordsText = if (coords != null && coords.size == 2) "${coords[0]}, ${coords[1]}" else "-"
        Text(
            text = "Koordinaten: ${coordsText}",
            style = MaterialTheme.typography.bodySmall
        )
        Divider(modifier = Modifier.padding(top= 12.dp))
    }
}










