package app.closer.ui.settings

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import app.closer.domain.repository.AuthRepository
import app.closer.domain.repository.SettingsRepository
import app.closer.domain.repository.UserRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.safeDrawingPadding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Divider
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import app.closer.R

data class NotificationSettingsUiState(
    val dailyReminderEnabled: Boolean = true,
    val partnerAnsweredEnabled: Boolean = true,
    val chatMessageEnabled: Boolean = true,
    val streakReminderEnabled: Boolean = false,
    val quietHoursEnabled: Boolean = false
)

@HiltViewModel
class NotificationSettingsViewModel @Inject constructor(
    private val settingsRepository: SettingsRepository,
    private val authRepository: AuthRepository,
    private val userRepository: UserRepository
) : ViewModel() {

    val uiState: StateFlow<NotificationSettingsUiState> = settingsRepository.settings
        .map { s ->
            NotificationSettingsUiState(
                dailyReminderEnabled = s.dailyReminderEnabled,
                partnerAnsweredEnabled = s.partnerAnsweredEnabled,
                chatMessageEnabled = s.chatMessageEnabled,
                streakReminderEnabled = s.streakReminderEnabled,
                quietHoursEnabled = s.quietHoursEnabled
            )
        }
        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), NotificationSettingsUiState())

    fun toggleDailyReminder(on: Boolean) = viewModelScope.launch {
        settingsRepository.setDailyReminder(on)
    }

    fun togglePartnerAnswered(on: Boolean) = viewModelScope.launch {
        settingsRepository.setPartnerAnswered(on)
        syncNotifPrefs(partnerAnswered = on, chatMessage = uiState.value.chatMessageEnabled)
    }

    fun toggleChatMessage(on: Boolean) = viewModelScope.launch {
        settingsRepository.setChatMessage(on)
        syncNotifPrefs(partnerAnswered = uiState.value.partnerAnsweredEnabled, chatMessage = on)
    }

    fun toggleStreakReminder(on: Boolean) = viewModelScope.launch {
        settingsRepository.setStreakReminder(on)
    }

    fun toggleQuietHours(on: Boolean) = viewModelScope.launch {
        settingsRepository.setQuietHours(on)
    }

    private fun syncNotifPrefs(partnerAnswered: Boolean, chatMessage: Boolean) {
        val uid = authRepository.currentUserId ?: return
        viewModelScope.launch {
            runCatching { userRepository.updateNotificationPrefs(uid, partnerAnswered, chatMessage) }
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun NotificationSettingsScreen(
    onNavigate: (String) -> Unit = {},
    viewModel: NotificationSettingsViewModel = hiltViewModel()
) {
    val state by viewModel.uiState.collectAsState()

    Scaffold(
        containerColor = Color.Transparent,
        modifier = Modifier.background(SettingsBackgroundBrush),
        topBar = {
            TopAppBar(
                title = { Text(stringResource(R.string.notifications_title), color = SettingsInk) },
                navigationIcon = {
                    IconButton(onClick = { onNavigate("back") }) {
                        Icon(
                            Icons.AutoMirrored.Filled.ArrowBack,
                            contentDescription = stringResource(R.string.action_back),
                            tint = SettingsInk
                        )
                    }
                },
                colors = TopAppBarDefaults.topAppBarColors(containerColor = Color.Transparent)
            )
        }
    ) { padding ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .safeDrawingPadding()
                .navigationBarsPadding()
                .verticalScroll(rememberScrollState())
                .padding(padding)
                .padding(horizontal = 16.dp, vertical = 8.dp),
            verticalArrangement = Arrangement.spacedBy(12.dp)
        ) {
            Text(
                text = stringResource(R.string.notifications_reminders_section),
                style = MaterialTheme.typography.labelLarge,
                color = SettingsMuted,
                modifier = Modifier.padding(horizontal = 4.dp, vertical = 4.dp)
            )

            Card(
                modifier = Modifier.fillMaxWidth(),
                shape = RoundedCornerShape(16.dp),
                colors = CardDefaults.cardColors(containerColor = SettingsCard)
            ) {
                Column {
                    NotifToggleRow(
                        label = stringResource(R.string.notifications_daily_question),
                        description = "A gentle nudge when today's question is ready",
                        checked = state.dailyReminderEnabled,
                        onCheckedChange = viewModel::toggleDailyReminder
                    )
                    Divider(modifier = Modifier.padding(horizontal = 16.dp), thickness = 0.5.dp)
                    NotifToggleRow(
                        label = stringResource(R.string.notifications_partner_answered),
                        description = "Let me know when they're ready to reveal",
                        checked = state.partnerAnsweredEnabled,
                        onCheckedChange = viewModel::togglePartnerAnswered
                    )
                    Divider(modifier = Modifier.padding(horizontal = 16.dp), thickness = 0.5.dp)
                    NotifToggleRow(
                        label = stringResource(R.string.notifications_chat_message),
                        description = "Notify me when my partner sends a message",
                        checked = state.chatMessageEnabled,
                        onCheckedChange = viewModel::toggleChatMessage
                    )
                    Divider(modifier = Modifier.padding(horizontal = 16.dp), thickness = 0.5.dp)
                    NotifToggleRow(
                        label = stringResource(R.string.notifications_streak_reminder),
                        description = "Remind me to keep our shared rhythm going",
                        checked = state.streakReminderEnabled,
                        onCheckedChange = viewModel::toggleStreakReminder
                    )
                }
            }

            Spacer(Modifier.height(4.dp))

            Text(
                text = stringResource(R.string.notifications_quiet_hours),
                style = MaterialTheme.typography.labelLarge,
                color = SettingsMuted,
                modifier = Modifier.padding(horizontal = 4.dp, vertical = 4.dp)
            )

            Card(
                modifier = Modifier.fillMaxWidth(),
                shape = RoundedCornerShape(16.dp),
                colors = CardDefaults.cardColors(containerColor = SettingsCard)
            ) {
                Column {
                    NotifToggleRow(
                        label = stringResource(R.string.notifications_quiet_hours),
                        description = stringResource(R.string.notifications_quiet_hours_desc),
                        checked = state.quietHoursEnabled,
                        onCheckedChange = viewModel::toggleQuietHours
                    )
                }
            }

            Spacer(Modifier.height(8.dp))

            Text(
                text = stringResource(R.string.notifications_footer),
                style = MaterialTheme.typography.bodySmall,
                color = SettingsMuted,
                modifier = Modifier.padding(horizontal = 4.dp)
            )
        }
    }
}

@Composable
private fun NotifToggleRow(
    label: String,
    description: String,
    checked: Boolean,
    onCheckedChange: (Boolean) -> Unit
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 16.dp, vertical = 14.dp),
        horizontalArrangement = Arrangement.SpaceBetween,
        verticalAlignment = Alignment.CenterVertically
    ) {
        Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) {
            Text(
                text = label,
                style = MaterialTheme.typography.bodyLarge,
                fontWeight = FontWeight.Medium,
                color = SettingsInk
            )
            Text(
                text = description,
                style = MaterialTheme.typography.bodySmall,
                color = SettingsMuted
            )
        }
        Switch(
            checked = checked,
            onCheckedChange = onCheckedChange,
            colors = settingsSwitchColors()
        )
    }
}

@Preview
@Composable
fun NotificationSettingsScreenPreview() {
    NotificationSettingsScreen()
}
