package com.isidroid.c23.ui.screen.print_jobs

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.ExperimentalMaterial3Api
import androidx.compose.material3.Scaffold
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.State
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import com.isidroid.c23.R
import com.isidroid.c23.ui._component.TopAppBarComponent
import com.isidroid.core.vm.SIDE_EFFECTS_KEY
import com.isidroid.ui.print_job.PrintJobListItemComponent
import kotlinx.coroutines.flow.Flow

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun PrintJobsScreen(
    state: State<PrintJobsContract.State>,
    effectFlow: Flow<PrintJobsContract.Effect>?,
    onEventSent: (event: PrintJobsContract.Event) -> Unit,
    onNavigationRequested: (navigationEffect: PrintJobsContract.Effect.Navigation) -> Unit,
    modifier: Modifier = Modifier,
) {
    LaunchedEffect(SIDE_EFFECTS_KEY) {
        effectFlow?.collect { effect ->
            when (effect) {
                is PrintJobsContract.Effect.Navigation -> onNavigationRequested(effect)
            }
        }
    }

    Scaffold(
        modifier = modifier.fillMaxSize(),
        topBar = {
            TopAppBarComponent(
                text = stringResource(id = R.string.print_job_list),
                colors = TopAppBarDefaults.topAppBarColors(),
                onNavigationClick = { onEventSent(PrintJobsContract.Event.ToBack) }
            )
        }
    ) { paddingValues ->

        ListComponent(
            state = state,
            modifier = Modifier.padding(paddingValues)
        )

    }
}

@Composable
private fun ListComponent(state: State<PrintJobsContract.State>, modifier: Modifier) {
    val list = state.value.jobs ?: return

    LazyColumn(modifier) {
        items(list) { item ->
            PrintJobListItemComponent(
                spotName = item.spotName,
                cost = item.cost,
                statusName = item.statusName,
                cover = item.cover,
                accessCode = item.accessCode,
                statusColor = item.statusColor,
                createdAt = item.createdAt,
                modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp)
            )
        }
    }
}