package de.haushalt.app.ui.task

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController

@Composable
fun TaskEditScreen(
    navController: NavController,
    taskId: Int,
    viewModel: TaskEditViewModel = viewModel(),
) {
    LaunchedEffect(taskId) {
        viewModel.load(taskId)
    }

    if (viewModel.isLoading) {
        Text("Lädt…", modifier = Modifier.padding(16.dp))
        return
    }

    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp),
        verticalArrangement = Arrangement.spacedBy(12.dp),
    ) {
        OutlinedTextField(
            value = viewModel.name,
            onValueChange = { viewModel.name = it },
            label = { Text("Name") },
            modifier = Modifier.fillMaxWidth(),
            singleLine = true,
        )

        DatePickerField(
            value = viewModel.date,
            onChange = { viewModel.date = it },
        )

        StatusDropdown(
            current = viewModel.status,
            selectable = viewModel.availableStatuses,
            onChange = { viewModel.status = it },
        )

        viewModel.error?.let {
            Text(it, color = MaterialTheme.colorScheme.error)
        }

        Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
            Button(
                enabled = !viewModel.isSubmitting && viewModel.name.isNotBlank(),
                onClick = { viewModel.update(taskId) { navController.popBackStack() } },
            ) {
                Text("Aktualisieren")
            }
            OutlinedButton(onClick = { navController.popBackStack() }) {
                Text("Abbrechen")
            }
        }
    }
}
