package de.haushalt.app.ui.schema

import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ExposedDropdownMenuBox
import androidx.compose.material3.ExposedDropdownMenuDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.MenuAnchorType
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
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.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import de.haushalt.app.data.TaskSchemaStatus
import de.haushalt.app.data.TaskStatus
import de.haushalt.app.ui.task.DatePickerField

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SchemaStatusDropdown(
    current: TaskSchemaStatus,
    onChange: (TaskSchemaStatus) -> Unit,
    modifier: Modifier = Modifier,
) {
    var expanded by remember { mutableStateOf(false) }
    ExposedDropdownMenuBox(expanded = expanded, onExpandedChange = { expanded = it }, modifier = modifier) {
        OutlinedTextField(
            value = current.name,
            onValueChange = {},
            readOnly = true,
            label = { Text("Schema Status") },
            trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded) },
            modifier = Modifier.fillMaxWidth().menuAnchor(MenuAnchorType.PrimaryNotEditable),
        )
        ExposedDropdownMenu(expanded = expanded, onDismissRequest = { expanded = false }) {
            TaskSchemaStatus.entries.forEach { status ->
                DropdownMenuItem(
                    text = { Text(status.name) },
                    onClick = { onChange(status); expanded = false },
                )
            }
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun TaskStatusDropdown(
    current: TaskStatus,
    onChange: (TaskStatus) -> Unit,
    modifier: Modifier = Modifier,
) {
    var expanded by remember { mutableStateOf(false) }
    val selectable = TaskStatus.entries.filter { it != TaskStatus.past }
    ExposedDropdownMenuBox(expanded = expanded, onExpandedChange = { expanded = it }, modifier = modifier) {
        OutlinedTextField(
            value = current.name,
            onValueChange = {},
            readOnly = true,
            label = { Text("Task Status") },
            trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded) },
            modifier = Modifier.fillMaxWidth().menuAnchor(MenuAnchorType.PrimaryNotEditable),
        )
        ExposedDropdownMenu(expanded = expanded, onDismissRequest = { expanded = false }) {
            selectable.forEach { status ->
                DropdownMenuItem(
                    text = { Text(status.name) },
                    onClick = { onChange(status); expanded = false },
                )
            }
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun RepeatTypeDropdown(
    current: String,
    onChange: (String) -> Unit,
) {
    val options = listOf("none" to "Keine (Einmalig)", "daily" to "Täglich", "weekly" to "Wöchentlich", "2week" to "2-Wöchentlich", "4week" to "4-Wöchentlich", "monthly" to "Monatlich", "days" to "Mehrere Tage")
    var expanded by remember { mutableStateOf(false) }
    ExposedDropdownMenuBox(expanded = expanded, onExpandedChange = { expanded = it }) {
        OutlinedTextField(
            value = options.firstOrNull { it.first == current }?.second ?: "",
            onValueChange = {},
            readOnly = true,
            label = { Text("Wiederholung") },
            trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded) },
            modifier = Modifier.fillMaxWidth().menuAnchor(MenuAnchorType.PrimaryNotEditable),
        )
        ExposedDropdownMenu(expanded = expanded, onDismissRequest = { expanded = false }) {
            options.forEach { (key, label) ->
                DropdownMenuItem(
                    text = { Text(label) },
                    onClick = { onChange(key); expanded = false },
                )
            }
        }
    }
}

@OptIn(ExperimentalLayoutApi::class)
@Composable
fun WeekdaySelector(
    selected: List<Boolean>,
    onChange: (List<Boolean>) -> Unit,
) {
    val days = listOf("Mo", "Di", "Mi", "Do", "Fr", "Sa", "So")
    Text("Wochentage", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
    FlowRow(horizontalArrangement = Arrangement.spacedBy(6.dp)) {
        days.forEachIndexed { i, day ->
            val isSelected = selected[i]
            Surface(
                modifier = Modifier.clickable {
                    onChange(selected.toMutableList().also { it[i] = !it[i] })
                },
                shape = RoundedCornerShape(6.dp),
                border = BorderStroke(1.dp, if (isSelected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.outline),
                color = if (isSelected) MaterialTheme.colorScheme.primaryContainer else MaterialTheme.colorScheme.surface,
            ) {
                Text(
                    text = day,
                    modifier = Modifier.padding(horizontal = 12.dp, vertical = 8.dp),
                    style = MaterialTheme.typography.bodyMedium,
                )
            }
        }
    }
}

@OptIn(ExperimentalLayoutApi::class)
@Composable
fun MonthdaySelector(
    selected: List<Boolean>,
    onChange: (List<Boolean>) -> Unit,
) {
    Text("Monatstage", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
    FlowRow(
        horizontalArrangement = Arrangement.spacedBy(4.dp),
        verticalArrangement = Arrangement.spacedBy(4.dp),
    ) {
        for (d in 1..31) {
            val isSelected = selected[d - 1]
            Surface(
                modifier = Modifier.size(40.dp).clickable {
                    onChange(selected.toMutableList().also { it[d - 1] = !it[d - 1] })
                },
                shape = RoundedCornerShape(6.dp),
                border = BorderStroke(1.dp, if (isSelected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.outline),
                color = if (isSelected) MaterialTheme.colorScheme.primaryContainer else MaterialTheme.colorScheme.surface,
            ) {
                Text(
                    text = "$d",
                    modifier = Modifier.padding(4.dp),
                    style = MaterialTheme.typography.bodySmall,
                )
            }
        }
    }
}

@Composable
fun DaysSelector(
    days: List<String>,
    onChange: (List<String>) -> Unit,
) {
    Text("Termine", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
    days.forEachIndexed { i, day ->
        Row(
            horizontalArrangement = Arrangement.spacedBy(8.dp),
            verticalAlignment = Alignment.CenterVertically,
        ) {
            DatePickerField(
                value = day,
                onChange = { newVal -> onChange(days.toMutableList().also { it[i] = newVal }) },
                label = "Datum",
                modifier = Modifier.weight(1f),
            )
            IconButton(onClick = { onChange(days.toMutableList().also { it.removeAt(i) }) }) {
                Icon(Icons.Filled.Delete, contentDescription = "Entfernen")
            }
        }
    }
    OutlinedButton(onClick = { onChange(days + "") }) {
        Icon(Icons.Filled.Add, contentDescription = null)
        Text("Termin")
    }
}
