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.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.tt.honeyDue.network.ApiResult
import com.tt.honeyDue.ui.theme.*
import com.tt.honeyDue.util.DateUtils
import com.tt.honeyDue.viewmodel.NotificationPreferencesViewModel
import com.tt.honeyDue.analytics.PostHogAnalytics
import com.tt.honeyDue.analytics.AnalyticsEvents
import honeydue.composeapp.generated.resources.*
import org.jetbrains.compose.resources.stringResource

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun NotificationPreferencesScreen(
    onNavigateBack: () -> Unit,
    viewModel: NotificationPreferencesViewModel = viewModel { NotificationPreferencesViewModel() }
) {
    val preferencesState by viewModel.preferencesState.collectAsState()
    val updateState by viewModel.updateState.collectAsState()

    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) }

    // Custom notification times (local hours)
    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) }

    // Time picker dialog states
    var showTaskDueSoonTimePicker by remember { mutableStateOf(false) }
    var showTaskOverdueTimePicker by remember { mutableStateOf(false) }
    var showDailyDigestTimePicker by remember { mutableStateOf(false) }

    // Default local hours when user first enables custom time
    val defaultTaskDueSoonLocalHour = 14  // 2 PM local
    val defaultTaskOverdueLocalHour = 9   // 9 AM local
    val defaultDailyDigestLocalHour = 8   // 8 AM local

    // Track screen view and load preferences on first render
    LaunchedEffect(Unit) {
        PostHogAnalytics.screen(AnalyticsEvents.NOTIFICATION_SETTINGS_SCREEN_SHOWN)
        viewModel.loadPreferences()
    }

    // Update local state when preferences load
    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

            // Load custom notification times (convert from UTC to local)
            prefs.taskDueSoonHour?.let { utcHour ->
                taskDueSoonHour = DateUtils.utcHourToLocal(utcHour)
            }
            prefs.taskOverdueHour?.let { utcHour ->
                taskOverdueHour = DateUtils.utcHourToLocal(utcHour)
            }
            prefs.warrantyExpiringHour?.let { utcHour ->
                warrantyExpiringHour = DateUtils.utcHourToLocal(utcHour)
            }
            prefs.dailyDigestHour?.let { utcHour ->
                dailyDigestHour = DateUtils.utcHourToLocal(utcHour)
            }
        }
    }

    WarmGradientBackground {
        Scaffold(
            containerColor = androidx.compose.ui.graphics.Color.Transparent,
            topBar = {
                TopAppBar(
                    title = { Text(stringResource(Res.string.notifications_title), fontWeight = FontWeight.SemiBold) },
                    navigationIcon = {
                        IconButton(onClick = onNavigateBack) {
                            Icon(Icons.Default.ArrowBack, contentDescription = stringResource(Res.string.common_back))
                        }
                    },
                    colors = TopAppBarDefaults.topAppBarColors(
                        containerColor = androidx.compose.ui.graphics.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
                        )
                    }
                }

                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 = null,
                                        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 -> {
                        // Task Notifications Section
                        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 {
                                NotificationToggle(
                                    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)
                                    }
                                )

                                // Time picker for Task Due Soon
                                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)
                                )

                                NotificationToggle(
                                    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)
                                    }
                                )

                                // Time picker for Task Overdue
                                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)
                                )

                                NotificationToggle(
                                    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)
                                )

                                NotificationToggle(
                                    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)
                                    }
                                )
                            }
                        }

                        // Time picker dialogs
                        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 }
                            )
                        }

                        // Other Notifications Section
                        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 {
                                NotificationToggle(
                                    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)
                                )

                                NotificationToggle(
                                    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)
                                )

                                NotificationToggle(
                                    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)
                                    }
                                )

                                // Time picker for Daily Digest
                                if (dailyDigest) {
                                    NotificationTimePickerRow(
                                        currentHour = dailyDigestHour,
                                        onSetCustomTime = {
                                            val localHour = defaultDailyDigestLocalHour
                                            dailyDigestHour = localHour
                                            val utcHour = DateUtils.localHourToUtc(localHour)
                                            viewModel.updatePreference(dailyDigestHour = utcHour)
                                        },
                                        onChangeTime = { showDailyDigestTimePicker = true }
                                    )
                                }
                            }
                        }

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

                        // Email Notifications Section
                        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 {
                                NotificationToggle(
                                    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))
                    }
                }
            }
        }
    }
}

@Composable
private fun NotificationToggle(
    title: String,
    description: String,
    icon: androidx.compose.ui.graphics.vector.ImageVector,
    iconTint: androidx.compose.ui.graphics.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,
            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,
            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
                )

                // Hour selector with AM/PM periods
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceEvenly
                ) {
                    // AM hours (6 AM - 11 AM)
                    Column(
                        horizontalAlignment = Alignment.CenterHorizontally,
                        verticalArrangement = Arrangement.spacedBy(OrganicSpacing.xs)
                    ) {
                        Text(
                            "AM",
                            style = MaterialTheme.typography.labelMedium,
                            fontWeight = FontWeight.SemiBold
                        )
                        (6..11).forEach { hour ->
                            HourChip(
                                hour = hour,
                                isSelected = selectedHour == hour,
                                onClick = { selectedHour = hour }
                            )
                        }
                    }

                    // PM hours (12 PM - 5 PM)
                    Column(
                        horizontalAlignment = Alignment.CenterHorizontally,
                        verticalArrangement = Arrangement.spacedBy(OrganicSpacing.xs)
                    ) {
                        Text(
                            "PM",
                            style = MaterialTheme.typography.labelMedium,
                            fontWeight = FontWeight.SemiBold
                        )
                        (12..17).forEach { hour ->
                            HourChip(
                                hour = hour,
                                isSelected = selectedHour == hour,
                                onClick = { selectedHour = hour }
                            )
                        }
                    }

                    // Evening hours (6 PM - 11 PM)
                    Column(
                        horizontalAlignment = Alignment.CenterHorizontally,
                        verticalArrangement = Arrangement.spacedBy(OrganicSpacing.xs)
                    ) {
                        Text(
                            "EVE",
                            style = MaterialTheme.typography.labelMedium,
                            fontWeight = FontWeight.SemiBold
                        )
                        (18..23).forEach { hour ->
                            HourChip(
                                hour = hour,
                                isSelected = selectedHour == hour,
                                onClick = { selectedHour = hour }
                            )
                        }
                    }
                }
            }
        },
        confirmButton = {
            TextButton(onClick = { onHourSelected(selectedHour) }) {
                Text(stringResource(Res.string.common_save))
            }
        },
        dismissButton = {
            TextButton(onClick = onDismiss) {
                Text(stringResource(Res.string.common_cancel))
            }
        }
    )
}

@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
        )
    }
}
