package com.example.todokotlin.ui

import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.example.todokotlin.data.Todo

@Composable
fun TodoFormDialog(
    todo: Todo? = null,
    onDismiss: () -> Unit,
    onSave: (title: String, category: String, priority: String) -> Unit
) {
    var title by remember { mutableStateOf(todo?.title ?: "") }
    var category by remember { mutableStateOf(todo?.category ?: "Personal") }
    var priority by remember { mutableStateOf(todo?.priority ?: "Medium") }

    val isEditing = todo != null
    val dialogTitle = if (isEditing) "Edit Todo" else "Add Todo"

    AlertDialog(
        onDismissRequest = onDismiss,
        title = { Text(dialogTitle) },
        text = {
            Column {
                OutlinedTextField(
                    value = title,
                    onValueChange = { title = it },
                    label = { Text("Title") },
                    singleLine = true,
                    modifier = Modifier.fillMaxWidth()
                )
                Spacer(modifier = Modifier.height(16.dp))
                CategoryPicker(
                    selected = category,
                    onSelect = { category = it }
                )
                Spacer(modifier = Modifier.height(12.dp))
                PriorityPicker(
                    selected = priority,
                    onSelect = { priority = it }
                )
            }
        },
        confirmButton = {
            TextButton(
                onClick = {
                    if (title.isNotBlank()) {
                        onSave(title.trim(), category, priority)
                    }
                },
                enabled = title.isNotBlank()
            ) {
                Text("Save")
            }
        },
        dismissButton = {
            TextButton(onClick = onDismiss) {
                Text("Cancel")
            }
        }
    )
}
