package de.ladkau.deckinadash.ui.config

import android.Manifest
import android.os.Build
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Button
import androidx.compose.material3.DatePicker
import androidx.compose.material3.DatePickerDialog
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ExposedDropdownMenuAnchorType
import androidx.compose.material3.ExposedDropdownMenuBox
import androidx.compose.material3.ExposedDropdownMenuDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.SegmentedButton
import androidx.compose.material3.SegmentedButtonDefaults
import androidx.compose.material3.SingleChoiceSegmentedButtonRow
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TimePicker
import androidx.compose.material3.rememberDatePickerState
import androidx.compose.material3.rememberTimePickerState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
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.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import androidx.compose.material3.AlertDialog
import androidx.lifecycle.viewmodel.compose.viewModel
import de.ladkau.deckinadash.R
import de.ladkau.deckinadash.data.Gender
import java.time.Instant
import java.time.ZoneOffset

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ConfigScreen(
    modifier: Modifier = Modifier,
    viewModel: ConfigViewModel = viewModel(),
) {
    val config by viewModel.config.collectAsState()
    val context = LocalContext.current

    var showDatePicker by remember { mutableStateOf(false) }
    var showBirthTimePicker by remember { mutableStateOf(false) }
    var showNotifyTimePicker by remember { mutableStateOf(false) }

    val notificationPermissionLauncher = rememberLauncherForActivityResult(
        ActivityResultContracts.RequestPermission(),
    ) { granted ->
        viewModel.update { it.copy(notifyEnabled = granted) }
    }

    Column(
        modifier = modifier
            .fillMaxWidth()
            .verticalScroll(rememberScrollState())
            .padding(16.dp),
        verticalArrangement = Arrangement.spacedBy(16.dp),
    ) {
        Text(stringResource(R.string.config_birth_date), style = MaterialTheme.typography.titleSmall)
        Button(onClick = { showDatePicker = true }) {
            val label = if (config.birthYear > 0) {
                "%04d-%02d-%02d".format(config.birthYear, config.birthMonth, config.birthDay)
            } else {
                stringResource(R.string.config_birth_date)
            }
            Text(label)
        }

        Text(stringResource(R.string.config_birth_time), style = MaterialTheme.typography.titleSmall)
        Button(onClick = { showBirthTimePicker = true }) {
            Text("%02d:%02d".format(config.birthHour, config.birthMinute))
        }

        OutlinedTextField(
            value = config.utcOffsetHours.toString(),
            onValueChange = { text ->
                text.toDoubleOrNull()?.let { value -> viewModel.update { it.copy(utcOffsetHours = value) } }
            },
            label = { Text(stringResource(R.string.config_utc_offset)) },
            keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(keyboardType = KeyboardType.Number),
        )
        OutlinedTextField(
            value = config.latitude.toString(),
            onValueChange = { text ->
                text.toDoubleOrNull()?.let { value -> viewModel.update { it.copy(latitude = value) } }
            },
            label = { Text(stringResource(R.string.config_latitude)) },
            keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(keyboardType = KeyboardType.Number),
        )
        OutlinedTextField(
            value = config.longitude.toString(),
            onValueChange = { text ->
                text.toDoubleOrNull()?.let { value -> viewModel.update { it.copy(longitude = value) } }
            },
            label = { Text(stringResource(R.string.config_longitude)) },
            keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(keyboardType = KeyboardType.Number),
        )

        Text(stringResource(R.string.config_gender), style = MaterialTheme.typography.titleSmall)
        val genderOptions = listOf(
            Gender.UNSPECIFIED to stringResource(R.string.config_gender_unspecified),
            Gender.MALE to stringResource(R.string.config_gender_male),
            Gender.FEMALE to stringResource(R.string.config_gender_female),
        )
        SingleChoiceSegmentedButtonRow {
            genderOptions.forEachIndexed { index, (gender, label) ->
                SegmentedButton(
                    shape = SegmentedButtonDefaults.itemShape(index = index, count = genderOptions.size),
                    selected = config.gender == gender,
                    onClick = { viewModel.update { it.copy(gender = gender) } },
                ) { Text(label) }
            }
        }

        LanguageDropdown(
            selected = config.lang,
            onSelected = { lang -> viewModel.update { it.copy(lang = lang) } },
        )

        Row {
            Text(stringResource(R.string.config_notify_enabled), style = MaterialTheme.typography.titleSmall)
            Switch(
                checked = config.notifyEnabled,
                onCheckedChange = { enabled ->
                    if (enabled && Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                        notificationPermissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)
                    } else {
                        viewModel.update { it.copy(notifyEnabled = enabled) }
                    }
                },
            )
        }
        if (config.notifyEnabled) {
            Button(onClick = { showNotifyTimePicker = true }) {
                Text("%02d:%02d".format(config.notifyHour, config.notifyMinute))
            }
        }

        Button(onClick = { viewModel.save {} }) {
            Text(stringResource(R.string.config_save))
        }
    }

    if (showDatePicker) {
        val initialMillis = runCatching {
            java.time.LocalDate.of(
                config.birthYear.takeIf { it > 0 } ?: 2000,
                config.birthMonth.takeIf { it in 1..12 } ?: 1,
                config.birthDay.takeIf { it in 1..31 } ?: 1,
            ).atStartOfDay(ZoneOffset.UTC).toInstant().toEpochMilli()
        }.getOrDefault(Instant.now().toEpochMilli())
        val datePickerState = rememberDatePickerState(initialSelectedDateMillis = initialMillis)
        DatePickerDialog(
            onDismissRequest = { showDatePicker = false },
            confirmButton = {
                TextButton(onClick = {
                    datePickerState.selectedDateMillis?.let { millis ->
                        val date = Instant.ofEpochMilli(millis).atZone(ZoneOffset.UTC).toLocalDate()
                        viewModel.update {
                            it.copy(birthYear = date.year, birthMonth = date.monthValue, birthDay = date.dayOfMonth)
                        }
                    }
                    showDatePicker = false
                }) { Text(stringResource(R.string.config_save)) }
            },
        ) { DatePicker(state = datePickerState) }
    }

    if (showBirthTimePicker) {
        TimePickerDialogContent(
            initialHour = config.birthHour,
            initialMinute = config.birthMinute,
            onDismiss = { showBirthTimePicker = false },
            onConfirm = { hour, minute ->
                viewModel.update { it.copy(birthHour = hour, birthMinute = minute) }
                showBirthTimePicker = false
            },
        )
    }

    if (showNotifyTimePicker) {
        TimePickerDialogContent(
            initialHour = config.notifyHour,
            initialMinute = config.notifyMinute,
            onDismiss = { showNotifyTimePicker = false },
            onConfirm = { hour, minute ->
                viewModel.update { it.copy(notifyHour = hour, notifyMinute = minute) }
                showNotifyTimePicker = false
            },
        )
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun TimePickerDialogContent(
    initialHour: Int,
    initialMinute: Int,
    onDismiss: () -> Unit,
    onConfirm: (hour: Int, minute: Int) -> Unit,
) {
    val state = rememberTimePickerState(initialHour = initialHour, initialMinute = initialMinute, is24Hour = true)
    AlertDialog(
        onDismissRequest = onDismiss,
        confirmButton = {
            TextButton(onClick = { onConfirm(state.hour, state.minute) }) {
                Text(stringResource(R.string.config_save))
            }
        },
        text = { TimePicker(state = state) },
    )
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun LanguageDropdown(selected: String, onSelected: (String) -> Unit) {
    var expanded by remember { mutableStateOf(false) }
    val languages = listOf("en", "de")
    ExposedDropdownMenuBox(expanded = expanded, onExpandedChange = { expanded = it }) {
        OutlinedTextField(
            value = selected,
            onValueChange = {},
            readOnly = true,
            label = { Text(stringResource(R.string.config_language)) },
            trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = expanded) },
            modifier = Modifier.fillMaxWidth().menuAnchor(ExposedDropdownMenuAnchorType.PrimaryNotEditable),
        )
        ExposedDropdownMenu(expanded = expanded, onDismissRequest = { expanded = false }) {
            languages.forEach { lang ->
                DropdownMenuItem(
                    text = { Text(lang) },
                    onClick = {
                        onSelected(lang)
                        expanded = false
                    },
                )
            }
        }
    }
}
