package com.tt.honeyDue.ui.screens

import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.tt.honeyDue.analytics.AnalyticsEvents
import com.tt.honeyDue.analytics.PostHogAnalytics
import com.tt.honeyDue.network.ApiResult
import com.tt.honeyDue.ui.theme.*
import com.tt.honeyDue.util.DateUtils
import com.tt.honeyDue.viewmodel.NotificationCategoriesController
import com.tt.honeyDue.viewmodel.NotificationCategoryKeys
import com.tt.honeyDue.viewmodel.NotificationPreferencesViewModel
import honeydue.composeapp.generated.resources.*
import org.jetbrains.compose.resources.StringResource
import org.jetbrains.compose.resources.stringResource

/**
 * Notification preferences screen — Android-first.
 *
 * Parity target: `iosApp/iosApp/Profile/NotificationPreferencesView.swift`.
 *
 * Rendered sections (top to bottom):
 *   1. Decorative header card.
 *   2. Per-category section (new, P4 Stream P). One row per channel id in
 *      [com.tt.honeyDue.notifications.NotificationChannels]:
 *         - task_reminder
 *         - task_overdue
 *         - residence_invite
 *         - subscription
 *      Each switch persists to DataStore via
 *      [NotificationCategoriesController] and rewrites the matching
 *      Android `NotificationChannel` importance to NONE when off.
 *   3. Master "All notifications" toggle (writes all four categories in
 *      one tap).
 *   4. Server-backed task / other / email sections (legacy preferences,
 *      unchanged — these still call the REST API).
 *   5. "Open system settings" button linking to
 *      `Settings.ACTION_APP_NOTIFICATION_SETTINGS`.
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun NotificationPreferencesScreen(
    onNavigateBack: () -> Unit,
    viewModel: NotificationPreferencesViewModel = viewModel { NotificationPreferencesViewModel() },
) {
    val preferencesState by viewModel.preferencesState.collectAsStateWithLifecycle()
    val categoryState by viewModel.categoryState.collectAsStateWithLifecycle()

    // Platform-specific wiring: Android provides real controller + settings
    // launcher; every other target returns null and the matching section
    // is hidden.
    val categoriesController = rememberNotificationCategoriesController()
    val openSystemSettings = rememberOpenAppNotificationSettings()

    // Legacy server-backed local state
    var taskDueSoon by remember { mutableStateOf(true) }
    var taskOverdue by remember { mutableStateOf(true) }
    var taskCompleted by remember { mutableStateOf(true) }
    var taskAssigned by remember { mutableStateOf(true) }
    var residenceShared by remember { mutableStateOf(true) }
    var warrantyExpiring by remember { mutableStateOf(true) }
    var dailyDigest by remember { mutableStateOf(true) }
    var emailTaskCompleted by remember { mutableStateOf(true) }

    var taskDueSoonHour by remember { mutableStateOf<Int?>(null) }
    var taskOverdueHour by remember { mutableStateOf<Int?>(null) }
    var warrantyExpiringHour by remember { mutableStateOf<Int?>(null) }
    var dailyDigestHour by remember { mutableStateOf<Int?>(null) }

    var showTaskDueSoonTimePicker by remember { mutableStateOf(false) }
    var showTaskOverdueTimePicker by remember { mutableStateOf(false) }
    var showDailyDigestTimePicker by remember { mutableStateOf(false) }

    val defaultTaskDueSoonLocalHour = 14
    val defaultTaskOverdueLocalHour = 9
    val defaultDailyDigestLocalHour = 8

    // Attach per-category controller (Android only) and load initial state.
    LaunchedEffect(categoriesController) {
        PostHogAnalytics.screen(AnalyticsEvents.NOTIFICATION_SETTINGS_SCREEN_SHOWN)
        viewModel.loadPreferences()
        if (categoriesController != null) {
            viewModel.attachCategoriesController(categoriesController)
        }
    }

    // Sync legacy server prefs into local state when they land.
    LaunchedEffect(preferencesState) {
        if (preferencesState is ApiResult.Success) {
            val prefs = (preferencesState as ApiResult.Success).data
            taskDueSoon = prefs.taskDueSoon
            taskOverdue = prefs.taskOverdue
            taskCompleted = prefs.taskCompleted
            taskAssigned = prefs.taskAssigned
            residenceShared = prefs.residenceShared
            warrantyExpiring = prefs.warrantyExpiring
            dailyDigest = prefs.dailyDigest
            emailTaskCompleted = prefs.emailTaskCompleted

            prefs.taskDueSoonHour?.let { taskDueSoonHour = DateUtils.utcHourToLocal(it) }
            prefs.taskOverdueHour?.let { taskOverdueHour = DateUtils.utcHourToLocal(it) }
            prefs.warrantyExpiringHour?.let { warrantyExpiringHour = DateUtils.utcHourToLocal(it) }
            prefs.dailyDigestHour?.let { dailyDigestHour = DateUtils.utcHourToLocal(it) }
        }
    }

    val masterEnabled = remember(categoryState) {
        NotificationCategoriesController.computeMasterState(categoryState)
    }

    WarmGradientBackground {
        Scaffold(
            containerColor = Color.Transparent,
            topBar = {
                TopAppBar(
                    title = {
                        Text(
                            stringResource(Res.string.notifications_title),
                            fontWeight = FontWeight.SemiBold,
                        )
                    },
                    navigationIcon = {
                        IconButton(onClick = onNavigateBack) {
                            Icon(
                                Icons.AutoMirrored.Filled.ArrowBack,
                                contentDescription = stringResource(Res.string.common_back),
                            )
                        }
                    },
                    colors = TopAppBarDefaults.topAppBarColors(
                        containerColor = Color.Transparent,
                    ),
                )
            },
        ) { paddingValues ->
            Column(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(paddingValues)
                    .verticalScroll(rememberScrollState())
                    .padding(horizontal = OrganicSpacing.lg, vertical = OrganicSpacing.md),
                verticalArrangement = Arrangement.spacedBy(OrganicSpacing.md),
            ) {
                // Header
                OrganicCard(modifier = Modifier.fillMaxWidth()) {
                    Column(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(OrganicSpacing.xl),
                        horizontalAlignment = Alignment.CenterHorizontally,
                        verticalArrangement = Arrangement.spacedBy(OrganicSpacing.md),
                    ) {
                        OrganicIconContainer(
                            icon = Icons.Default.Notifications,
                            size = 60.dp,
                        )
                        Text(
                            stringResource(Res.string.notifications_preferences),
                            style = MaterialTheme.typography.titleLarge,
                            fontWeight = FontWeight.Bold,
                        )
                        Text(
                            stringResource(Res.string.notifications_choose),
                            style = MaterialTheme.typography.bodyMedium,
                            color = MaterialTheme.colorScheme.onSurfaceVariant,
                        )
                    }
                }

                // -----------------------------------------------------------------
                // Master toggle (P4 Stream P) — only shown when we have a real
                // controller (Android). On other platforms the section is hidden.
                // -----------------------------------------------------------------
                if (categoriesController != null) {
                    OrganicCard(modifier = Modifier.fillMaxWidth()) {
                        NotificationToggleRow(
                            title = stringResource(Res.string.notifications_master_title),
                            description = stringResource(Res.string.notifications_master_desc),
                            icon = Icons.Default.NotificationsActive,
                            iconTint = MaterialTheme.colorScheme.primary,
                            checked = masterEnabled,
                            onCheckedChange = { viewModel.toggleMaster(it) },
                        )
                    }

                    Text(
                        stringResource(Res.string.notifications_categories_section),
                        style = MaterialTheme.typography.titleMedium,
                        fontWeight = FontWeight.SemiBold,
                        modifier = Modifier.padding(top = OrganicSpacing.md),
                    )

                    OrganicCard(modifier = Modifier.fillMaxWidth()) {
                        Column {
                            CategoryRows.forEachIndexed { index, cat ->
                                NotificationToggleRow(
                                    title = stringResource(cat.titleRes),
                                    description = stringResource(cat.descRes),
                                    icon = cat.icon,
                                    iconTint = cat.tint(),
                                    checked = categoryState[cat.channelId] ?: true,
                                    onCheckedChange = { enabled ->
                                        viewModel.toggleCategory(cat.channelId, enabled)
                                    },
                                )
                                if (index != CategoryRows.lastIndex) {
                                    OrganicDivider(
                                        modifier = Modifier.padding(horizontal = OrganicSpacing.lg),
                                    )
                                }
                            }
                        }
                    }

                    if (openSystemSettings != null) {
                        OrganicCard(modifier = Modifier.fillMaxWidth()) {
                            Row(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .clickable { openSystemSettings() }
                                    .padding(OrganicSpacing.lg),
                                horizontalArrangement = Arrangement.spacedBy(OrganicSpacing.md),
                                verticalAlignment = Alignment.CenterVertically,
                            ) {
                                Icon(
                                    imageVector = Icons.Default.Settings,
                                    contentDescription = stringResource(Res.string.notifications_open_system_settings),
                                    tint = MaterialTheme.colorScheme.primary,
                                )
                                Column(modifier = Modifier.weight(1f)) {
                                    Text(
                                        stringResource(Res.string.notifications_open_system_settings),
                                        style = MaterialTheme.typography.bodyLarge,
                                        fontWeight = FontWeight.Medium,
                                    )
                                    Text(
                                        stringResource(Res.string.notifications_system_settings_desc),
                                        style = MaterialTheme.typography.bodySmall,
                                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                                    )
                                }
                                Icon(
                                    imageVector = Icons.Default.ChevronRight,
                                    contentDescription = null, // decorative
                                    tint = MaterialTheme.colorScheme.onSurfaceVariant,
                                )
                            }
                        }
                    }
                }

                // -----------------------------------------------------------------
                // Legacy server-backed sections (unchanged)
                // -----------------------------------------------------------------
                when (preferencesState) {
                    is ApiResult.Loading -> {
                        Box(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(OrganicSpacing.xl),
                            contentAlignment = Alignment.Center,
                        ) {
                            CircularProgressIndicator()
                        }
                    }

                    is ApiResult.Error -> {
                        OrganicCard(
                            modifier = Modifier.fillMaxWidth(),
                            accentColor = MaterialTheme.colorScheme.errorContainer,
                        ) {
                            Column(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(OrganicSpacing.lg),
                                verticalArrangement = Arrangement.spacedBy(OrganicSpacing.md),
                            ) {
                                Row(
                                    horizontalArrangement = Arrangement.spacedBy(OrganicSpacing.md),
                                    verticalAlignment = Alignment.CenterVertically,
                                ) {
                                    Icon(
                                        Icons.Default.Error,
                                        contentDescription = "Error",
                                        tint = MaterialTheme.colorScheme.error,
                                    )
                                    Text(
                                        (preferencesState as ApiResult.Error).message,
                                        color = MaterialTheme.colorScheme.error,
                                        style = MaterialTheme.typography.bodyMedium,
                                        fontWeight = FontWeight.SemiBold,
                                    )
                                }
                                OrganicPrimaryButton(
                                    text = stringResource(Res.string.common_retry),
                                    onClick = { viewModel.loadPreferences() },
                                    modifier = Modifier.fillMaxWidth(),
                                )
                            }
                        }
                    }

                    is ApiResult.Success, is ApiResult.Idle -> {
                        Text(
                            stringResource(Res.string.notifications_task_section),
                            style = MaterialTheme.typography.titleMedium,
                            fontWeight = FontWeight.SemiBold,
                            modifier = Modifier.padding(top = OrganicSpacing.md),
                        )

                        OrganicCard(modifier = Modifier.fillMaxWidth()) {
                            Column {
                                NotificationToggleRow(
                                    title = stringResource(Res.string.notifications_task_due_soon),
                                    description = stringResource(Res.string.notifications_task_due_soon_desc),
                                    icon = Icons.Default.Schedule,
                                    iconTint = MaterialTheme.colorScheme.tertiary,
                                    checked = taskDueSoon,
                                    onCheckedChange = {
                                        taskDueSoon = it
                                        viewModel.updatePreference(taskDueSoon = it)
                                    },
                                )
                                if (taskDueSoon) {
                                    NotificationTimePickerRow(
                                        currentHour = taskDueSoonHour,
                                        onSetCustomTime = {
                                            val localHour = defaultTaskDueSoonLocalHour
                                            taskDueSoonHour = localHour
                                            val utcHour = DateUtils.localHourToUtc(localHour)
                                            viewModel.updatePreference(taskDueSoonHour = utcHour)
                                        },
                                        onChangeTime = { showTaskDueSoonTimePicker = true },
                                    )
                                }
                                OrganicDivider(modifier = Modifier.padding(horizontal = OrganicSpacing.lg))

                                NotificationToggleRow(
                                    title = stringResource(Res.string.notifications_task_overdue),
                                    description = stringResource(Res.string.notifications_task_overdue_desc),
                                    icon = Icons.Default.Warning,
                                    iconTint = MaterialTheme.colorScheme.error,
                                    checked = taskOverdue,
                                    onCheckedChange = {
                                        taskOverdue = it
                                        viewModel.updatePreference(taskOverdue = it)
                                    },
                                )
                                if (taskOverdue) {
                                    NotificationTimePickerRow(
                                        currentHour = taskOverdueHour,
                                        onSetCustomTime = {
                                            val localHour = defaultTaskOverdueLocalHour
                                            taskOverdueHour = localHour
                                            val utcHour = DateUtils.localHourToUtc(localHour)
                                            viewModel.updatePreference(taskOverdueHour = utcHour)
                                        },
                                        onChangeTime = { showTaskOverdueTimePicker = true },
                                    )
                                }
                                OrganicDivider(modifier = Modifier.padding(horizontal = OrganicSpacing.lg))

                                NotificationToggleRow(
                                    title = stringResource(Res.string.notifications_task_completed),
                                    description = stringResource(Res.string.notifications_task_completed_desc),
                                    icon = Icons.Default.CheckCircle,
                                    iconTint = MaterialTheme.colorScheme.primary,
                                    checked = taskCompleted,
                                    onCheckedChange = {
                                        taskCompleted = it
                                        viewModel.updatePreference(taskCompleted = it)
                                    },
                                )
                                OrganicDivider(modifier = Modifier.padding(horizontal = OrganicSpacing.lg))

                                NotificationToggleRow(
                                    title = stringResource(Res.string.notifications_task_assigned),
                                    description = stringResource(Res.string.notifications_task_assigned_desc),
                                    icon = Icons.Default.PersonAdd,
                                    iconTint = MaterialTheme.colorScheme.secondary,
                                    checked = taskAssigned,
                                    onCheckedChange = {
                                        taskAssigned = it
                                        viewModel.updatePreference(taskAssigned = it)
                                    },
                                )
                            }
                        }

                        if (showTaskDueSoonTimePicker) {
                            HourPickerDialog(
                                currentHour = taskDueSoonHour ?: defaultTaskDueSoonLocalHour,
                                onHourSelected = { hour ->
                                    taskDueSoonHour = hour
                                    val utcHour = DateUtils.localHourToUtc(hour)
                                    viewModel.updatePreference(taskDueSoonHour = utcHour)
                                    showTaskDueSoonTimePicker = false
                                },
                                onDismiss = { showTaskDueSoonTimePicker = false },
                            )
                        }
                        if (showTaskOverdueTimePicker) {
                            HourPickerDialog(
                                currentHour = taskOverdueHour ?: defaultTaskOverdueLocalHour,
                                onHourSelected = { hour ->
                                    taskOverdueHour = hour
                                    val utcHour = DateUtils.localHourToUtc(hour)
                                    viewModel.updatePreference(taskOverdueHour = utcHour)
                                    showTaskOverdueTimePicker = false
                                },
                                onDismiss = { showTaskOverdueTimePicker = false },
                            )
                        }

                        Text(
                            stringResource(Res.string.notifications_other_section),
                            style = MaterialTheme.typography.titleMedium,
                            fontWeight = FontWeight.SemiBold,
                            modifier = Modifier.padding(top = OrganicSpacing.md),
                        )

                        OrganicCard(modifier = Modifier.fillMaxWidth()) {
                            Column {
                                NotificationToggleRow(
                                    title = stringResource(Res.string.notifications_property_shared),
                                    description = stringResource(Res.string.notifications_property_shared_desc),
                                    icon = Icons.Default.Home,
                                    iconTint = MaterialTheme.colorScheme.primary,
                                    checked = residenceShared,
                                    onCheckedChange = {
                                        residenceShared = it
                                        viewModel.updatePreference(residenceShared = it)
                                    },
                                )
                                OrganicDivider(modifier = Modifier.padding(horizontal = OrganicSpacing.lg))

                                NotificationToggleRow(
                                    title = stringResource(Res.string.notifications_warranty_expiring),
                                    description = stringResource(Res.string.notifications_warranty_expiring_desc),
                                    icon = Icons.Default.Description,
                                    iconTint = MaterialTheme.colorScheme.tertiary,
                                    checked = warrantyExpiring,
                                    onCheckedChange = {
                                        warrantyExpiring = it
                                        viewModel.updatePreference(warrantyExpiring = it)
                                    },
                                )
                                OrganicDivider(modifier = Modifier.padding(horizontal = OrganicSpacing.lg))

                                NotificationToggleRow(
                                    title = stringResource(Res.string.notifications_daily_digest),
                                    description = stringResource(Res.string.notifications_daily_digest_desc),
                                    icon = Icons.Default.Summarize,
                                    iconTint = MaterialTheme.colorScheme.secondary,
                                    checked = dailyDigest,
                                    onCheckedChange = {
                                        dailyDigest = it
                                        viewModel.updatePreference(dailyDigest = it)
                                    },
                                )
                                if (dailyDigest) {
                                    NotificationTimePickerRow(
                                        currentHour = dailyDigestHour,
                                        onSetCustomTime = {
                                            val localHour = defaultDailyDigestLocalHour
                                            dailyDigestHour = localHour
                                            val utcHour = DateUtils.localHourToUtc(localHour)
                                            viewModel.updatePreference(dailyDigestHour = utcHour)
                                        },
                                        onChangeTime = { showDailyDigestTimePicker = true },
                                    )
                                }
                            }
                        }

                        if (showDailyDigestTimePicker) {
                            HourPickerDialog(
                                currentHour = dailyDigestHour ?: defaultDailyDigestLocalHour,
                                onHourSelected = { hour ->
                                    dailyDigestHour = hour
                                    val utcHour = DateUtils.localHourToUtc(hour)
                                    viewModel.updatePreference(dailyDigestHour = utcHour)
                                    showDailyDigestTimePicker = false
                                },
                                onDismiss = { showDailyDigestTimePicker = false },
                            )
                        }

                        Text(
                            stringResource(Res.string.notifications_email_section),
                            style = MaterialTheme.typography.titleMedium,
                            fontWeight = FontWeight.SemiBold,
                            modifier = Modifier.padding(top = OrganicSpacing.md),
                        )

                        OrganicCard(modifier = Modifier.fillMaxWidth()) {
                            Column {
                                NotificationToggleRow(
                                    title = stringResource(Res.string.notifications_email_task_completed),
                                    description = stringResource(Res.string.notifications_email_task_completed_desc),
                                    icon = Icons.Default.Email,
                                    iconTint = MaterialTheme.colorScheme.primary,
                                    checked = emailTaskCompleted,
                                    onCheckedChange = {
                                        emailTaskCompleted = it
                                        viewModel.updatePreference(emailTaskCompleted = it)
                                    },
                                )
                            }
                        }

                        Spacer(modifier = Modifier.height(OrganicSpacing.xl))
                    }
                }
            }
        }
    }
}

/**
 * Metadata for the four per-category rows. Order matches
 * [NotificationCategoryKeys.ALL].
 */
private data class NotificationCategoryRow(
    val channelId: String,
    val titleRes: StringResource,
    val descRes: StringResource,
    val icon: ImageVector,
    val tint: @Composable () -> Color,
)

private val CategoryRows: List<NotificationCategoryRow> = listOf(
    NotificationCategoryRow(
        channelId = NotificationCategoryKeys.TASK_REMINDER,
        titleRes = Res.string.notifications_category_task_reminder,
        descRes = Res.string.notifications_category_task_reminder_desc,
        icon = Icons.Default.Schedule,
        tint = { MaterialTheme.colorScheme.tertiary },
    ),
    NotificationCategoryRow(
        channelId = NotificationCategoryKeys.TASK_OVERDUE,
        titleRes = Res.string.notifications_category_task_overdue,
        descRes = Res.string.notifications_category_task_overdue_desc,
        icon = Icons.Default.Warning,
        tint = { MaterialTheme.colorScheme.error },
    ),
    NotificationCategoryRow(
        channelId = NotificationCategoryKeys.RESIDENCE_INVITE,
        titleRes = Res.string.notifications_category_residence_invite,
        descRes = Res.string.notifications_category_residence_invite_desc,
        icon = Icons.Default.Home,
        tint = { MaterialTheme.colorScheme.primary },
    ),
    NotificationCategoryRow(
        channelId = NotificationCategoryKeys.SUBSCRIPTION,
        titleRes = Res.string.notifications_category_subscription,
        descRes = Res.string.notifications_category_subscription_desc,
        icon = Icons.Default.Star,
        tint = { MaterialTheme.colorScheme.secondary },
    ),
)

@Composable
private fun NotificationToggleRow(
    title: String,
    description: String,
    icon: ImageVector,
    iconTint: Color,
    checked: Boolean,
    onCheckedChange: (Boolean) -> Unit,
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(OrganicSpacing.lg),
        horizontalArrangement = Arrangement.spacedBy(OrganicSpacing.md),
        verticalAlignment = Alignment.CenterVertically,
    ) {
        Icon(
            imageVector = icon,
            contentDescription = null, // decorative
            tint = iconTint,
        )
        Column(
            modifier = Modifier.weight(1f),
            verticalArrangement = Arrangement.spacedBy(2.dp),
        ) {
            Text(
                text = title,
                style = MaterialTheme.typography.bodyLarge,
                fontWeight = FontWeight.Medium,
            )
            Text(
                text = description,
                style = MaterialTheme.typography.bodySmall,
                color = MaterialTheme.colorScheme.onSurfaceVariant,
            )
        }
        Switch(
            checked = checked,
            onCheckedChange = onCheckedChange,
            colors = SwitchDefaults.colors(
                checkedThumbColor = MaterialTheme.colorScheme.onPrimary,
                checkedTrackColor = MaterialTheme.colorScheme.primary,
            ),
        )
    }
}

@Composable
private fun NotificationTimePickerRow(
    currentHour: Int?,
    onSetCustomTime: () -> Unit,
    onChangeTime: () -> Unit,
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(
                start = OrganicSpacing.lg + 24.dp + OrganicSpacing.md,
                end = OrganicSpacing.lg,
                bottom = OrganicSpacing.md,
            ),
        horizontalArrangement = Arrangement.spacedBy(OrganicSpacing.sm),
        verticalAlignment = Alignment.CenterVertically,
    ) {
        Icon(
            imageVector = Icons.Default.AccessTime,
            contentDescription = null, // decorative
            modifier = Modifier.size(16.dp),
            tint = MaterialTheme.colorScheme.onSurfaceVariant,
        )
        if (currentHour != null) {
            Text(
                text = DateUtils.formatHour(currentHour),
                style = MaterialTheme.typography.bodySmall,
                color = MaterialTheme.colorScheme.primary,
                fontWeight = FontWeight.Medium,
            )
            Text(
                text = stringResource(Res.string.notifications_change_time),
                style = MaterialTheme.typography.bodySmall,
                color = MaterialTheme.colorScheme.primary,
                modifier = Modifier.clickable { onChangeTime() },
            )
        } else {
            Text(
                text = stringResource(Res.string.notifications_set_custom_time),
                style = MaterialTheme.typography.bodySmall,
                color = MaterialTheme.colorScheme.primary,
                modifier = Modifier.clickable { onSetCustomTime() },
            )
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun HourPickerDialog(
    currentHour: Int,
    onHourSelected: (Int) -> Unit,
    onDismiss: () -> Unit,
) {
    var selectedHour by remember { mutableStateOf(currentHour) }

    AlertDialog(
        onDismissRequest = onDismiss,
        title = {
            Text(
                stringResource(Res.string.notifications_select_time),
                fontWeight = FontWeight.SemiBold,
            )
        },
        text = {
            Column(
                modifier = Modifier.fillMaxWidth(),
                horizontalAlignment = Alignment.CenterHorizontally,
                verticalArrangement = Arrangement.spacedBy(OrganicSpacing.md),
            ) {
                Text(
                    text = DateUtils.formatHour(selectedHour),
                    style = MaterialTheme.typography.headlineMedium,
                    fontWeight = FontWeight.Bold,
                    color = MaterialTheme.colorScheme.primary,
                )
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceEvenly,
                ) {
                    HourColumn(label = "AM", range = 6..11, selectedHour = selectedHour) {
                        selectedHour = it
                    }
                    HourColumn(label = "PM", range = 12..17, selectedHour = selectedHour) {
                        selectedHour = it
                    }
                    HourColumn(label = "EVE", range = 18..23, selectedHour = selectedHour) {
                        selectedHour = it
                    }
                }
            }
        },
        confirmButton = {
            TextButton(onClick = { onHourSelected(selectedHour) }) {
                Text(stringResource(Res.string.common_save))
            }
        },
        dismissButton = {
            TextButton(onClick = onDismiss) {
                Text(stringResource(Res.string.common_cancel))
            }
        },
    )
}

@Composable
private fun HourColumn(
    label: String,
    range: IntRange,
    selectedHour: Int,
    onSelect: (Int) -> Unit,
) {
    Column(
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.spacedBy(OrganicSpacing.xs),
    ) {
        Text(
            label,
            style = MaterialTheme.typography.labelMedium,
            fontWeight = FontWeight.SemiBold,
        )
        range.forEach { hour ->
            HourChip(
                hour = hour,
                isSelected = selectedHour == hour,
                onClick = { onSelect(hour) },
            )
        }
    }
}

@Composable
private fun HourChip(
    hour: Int,
    isSelected: Boolean,
    onClick: () -> Unit,
) {
    val displayHour = when {
        hour == 0 -> "12"
        hour > 12 -> "${hour - 12}"
        else -> "$hour"
    }
    val amPm = if (hour < 12) "AM" else "PM"

    Surface(
        modifier = Modifier
            .width(56.dp)
            .clickable { onClick() },
        shape = OrganicShapes.small,
        color = if (isSelected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.surfaceVariant,
    ) {
        Text(
            text = "$displayHour $amPm",
            style = MaterialTheme.typography.bodySmall,
            fontWeight = if (isSelected) FontWeight.Bold else FontWeight.Normal,
            color = if (isSelected) MaterialTheme.colorScheme.onPrimary else MaterialTheme.colorScheme.onSurfaceVariant,
            modifier = Modifier.padding(
                horizontal = OrganicSpacing.sm,
                vertical = OrganicSpacing.xs,
            ),
            textAlign = androidx.compose.ui.text.style.TextAlign.Center,
        )
    }
}
