package com.seven.ikar.kotlin.core.settings

import android.content.Context
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow

enum class ChatListLayoutOption {
    TwoLine,
    ThreeLine
}

enum class ChatSwipeLeftActionOption {
    Delete,
    Archive,
    Mute,
    Read
}

enum class ChatDistanceUnitOption {
    Automatic,
    Kilometers,
    Miles
}

const val DEFAULT_CHAT_WALLPAPER_PRESET_ID = "mint_field"

data class ChatSettingsSnapshot(
    val messageTextSizeSp: Int = 18,
    val bubbleCornerRadiusDp: Int = 11,
    val selectedWallpaperPresetId: String = DEFAULT_CHAT_WALLPAPER_PRESET_ID,
    val customWallpaperUri: String? = null,
    val useCustomWallpaper: Boolean = false,
    val chatListLayout: ChatListLayoutOption = ChatListLayoutOption.TwoLine,
    val swipeLeftAction: ChatSwipeLeftActionOption = ChatSwipeLeftActionOption.Delete,
    val autoNightThemeEnabled: Boolean = false,
    val inAppBrowserEnabled: Boolean = true,
    val animationsEnabled: Boolean = true,
    val mediaTapToBrowseEnabled: Boolean = true,
    val raiseToListenEnabled: Boolean = true,
    val raiseToTalkEnabled: Boolean = false,
    val pauseMusicOnRecordEnabled: Boolean = true,
    val pauseMusicOnPlaybackEnabled: Boolean = false,
    val directShareEnabled: Boolean = true,
    val showSensitiveContentEnabled: Boolean = false,
    val sendByEnterEnabled: Boolean = false,
    val distanceUnit: ChatDistanceUnitOption = ChatDistanceUnitOption.Automatic
)

class AndroidChatSettings(context: Context) {
    private val preferences = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE)
    private val _snapshot = MutableStateFlow(loadSnapshot())
    val snapshot: StateFlow<ChatSettingsSnapshot> = _snapshot.asStateFlow()

    fun loadSnapshot(): ChatSettingsSnapshot =
        ChatSettingsSnapshot(
            messageTextSizeSp = preferences.getInt(KEY_MESSAGE_TEXT_SIZE_SP, DEFAULT_MESSAGE_TEXT_SIZE_SP)
                .coerceIn(14, 26),
            bubbleCornerRadiusDp = preferences.getInt(KEY_BUBBLE_CORNER_RADIUS_DP, DEFAULT_BUBBLE_CORNER_RADIUS_DP)
                .coerceIn(4, 24),
            selectedWallpaperPresetId = preferences
                .getString(KEY_SELECTED_WALLPAPER_PRESET_ID, DEFAULT_CHAT_WALLPAPER_PRESET_ID)
                .orEmpty()
                .ifBlank { DEFAULT_CHAT_WALLPAPER_PRESET_ID },
            customWallpaperUri = preferences.getString(KEY_CUSTOM_WALLPAPER_URI, null),
            useCustomWallpaper = preferences.getBoolean(KEY_USE_CUSTOM_WALLPAPER, false),
            chatListLayout = getEnum(KEY_CHAT_LIST_LAYOUT, ChatListLayoutOption.TwoLine),
            swipeLeftAction = getEnum(KEY_SWIPE_LEFT_ACTION, ChatSwipeLeftActionOption.Delete),
            autoNightThemeEnabled = preferences.getBoolean(KEY_AUTO_NIGHT_THEME_ENABLED, false),
            inAppBrowserEnabled = preferences.getBoolean(KEY_IN_APP_BROWSER_ENABLED, true),
            animationsEnabled = preferences.getBoolean(KEY_ANIMATIONS_ENABLED, true),
            mediaTapToBrowseEnabled = preferences.getBoolean(KEY_MEDIA_TAP_TO_BROWSE_ENABLED, true),
            raiseToListenEnabled = preferences.getBoolean(KEY_RAISE_TO_LISTEN_ENABLED, true),
            raiseToTalkEnabled = preferences.getBoolean(KEY_RAISE_TO_TALK_ENABLED, false),
            pauseMusicOnRecordEnabled = preferences.getBoolean(KEY_PAUSE_MUSIC_ON_RECORD_ENABLED, true),
            pauseMusicOnPlaybackEnabled = preferences.getBoolean(KEY_PAUSE_MUSIC_ON_PLAYBACK_ENABLED, false),
            directShareEnabled = preferences.getBoolean(KEY_DIRECT_SHARE_ENABLED, true),
            showSensitiveContentEnabled = preferences.getBoolean(KEY_SHOW_SENSITIVE_CONTENT_ENABLED, false),
            sendByEnterEnabled = preferences.getBoolean(KEY_SEND_BY_ENTER_ENABLED, false),
            distanceUnit = getEnum(KEY_DISTANCE_UNIT, ChatDistanceUnitOption.Automatic)
        )

    fun update(transform: (ChatSettingsSnapshot) -> ChatSettingsSnapshot) {
        saveSnapshot(transform(_snapshot.value))
    }

    fun saveSnapshot(snapshot: ChatSettingsSnapshot) {
        preferences.edit().apply {
            putInt(KEY_MESSAGE_TEXT_SIZE_SP, snapshot.messageTextSizeSp.coerceIn(14, 26))
            putInt(KEY_BUBBLE_CORNER_RADIUS_DP, snapshot.bubbleCornerRadiusDp.coerceIn(4, 24))
            putString(
                KEY_SELECTED_WALLPAPER_PRESET_ID,
                snapshot.selectedWallpaperPresetId.ifBlank { DEFAULT_CHAT_WALLPAPER_PRESET_ID }
            )
            putString(KEY_CUSTOM_WALLPAPER_URI, snapshot.customWallpaperUri)
            putBoolean(KEY_USE_CUSTOM_WALLPAPER, snapshot.useCustomWallpaper)
            putString(KEY_CHAT_LIST_LAYOUT, snapshot.chatListLayout.name)
            putString(KEY_SWIPE_LEFT_ACTION, snapshot.swipeLeftAction.name)
            putBoolean(KEY_AUTO_NIGHT_THEME_ENABLED, snapshot.autoNightThemeEnabled)
            putBoolean(KEY_IN_APP_BROWSER_ENABLED, snapshot.inAppBrowserEnabled)
            putBoolean(KEY_ANIMATIONS_ENABLED, snapshot.animationsEnabled)
            putBoolean(KEY_MEDIA_TAP_TO_BROWSE_ENABLED, snapshot.mediaTapToBrowseEnabled)
            putBoolean(KEY_RAISE_TO_LISTEN_ENABLED, snapshot.raiseToListenEnabled)
            putBoolean(KEY_RAISE_TO_TALK_ENABLED, snapshot.raiseToTalkEnabled)
            putBoolean(KEY_PAUSE_MUSIC_ON_RECORD_ENABLED, snapshot.pauseMusicOnRecordEnabled)
            putBoolean(KEY_PAUSE_MUSIC_ON_PLAYBACK_ENABLED, snapshot.pauseMusicOnPlaybackEnabled)
            putBoolean(KEY_DIRECT_SHARE_ENABLED, snapshot.directShareEnabled)
            putBoolean(KEY_SHOW_SENSITIVE_CONTENT_ENABLED, snapshot.showSensitiveContentEnabled)
            putBoolean(KEY_SEND_BY_ENTER_ENABLED, snapshot.sendByEnterEnabled)
            putString(KEY_DISTANCE_UNIT, snapshot.distanceUnit.name)
            apply()
        }
        _snapshot.value = snapshot.copy(
            messageTextSizeSp = snapshot.messageTextSizeSp.coerceIn(14, 26),
            bubbleCornerRadiusDp = snapshot.bubbleCornerRadiusDp.coerceIn(4, 24)
        )
    }

    fun reset() {
        preferences.edit().apply {
            remove(KEY_MESSAGE_TEXT_SIZE_SP)
            remove(KEY_BUBBLE_CORNER_RADIUS_DP)
            remove(KEY_SELECTED_WALLPAPER_PRESET_ID)
            remove(KEY_CUSTOM_WALLPAPER_URI)
            remove(KEY_USE_CUSTOM_WALLPAPER)
            remove(KEY_CHAT_LIST_LAYOUT)
            remove(KEY_SWIPE_LEFT_ACTION)
            remove(KEY_AUTO_NIGHT_THEME_ENABLED)
            remove(KEY_IN_APP_BROWSER_ENABLED)
            remove(KEY_ANIMATIONS_ENABLED)
            remove(KEY_MEDIA_TAP_TO_BROWSE_ENABLED)
            remove(KEY_RAISE_TO_LISTEN_ENABLED)
            remove(KEY_RAISE_TO_TALK_ENABLED)
            remove(KEY_PAUSE_MUSIC_ON_RECORD_ENABLED)
            remove(KEY_PAUSE_MUSIC_ON_PLAYBACK_ENABLED)
            remove(KEY_DIRECT_SHARE_ENABLED)
            remove(KEY_SHOW_SENSITIVE_CONTENT_ENABLED)
            remove(KEY_SEND_BY_ENTER_ENABLED)
            remove(KEY_DISTANCE_UNIT)
            apply()
        }
        _snapshot.value = ChatSettingsSnapshot()
    }

    private fun <T : Enum<T>> getEnum(key: String, defaultValue: T): T {
        val rawValue = preferences.getString(key, defaultValue.name).orEmpty()
        @Suppress("UNCHECKED_CAST")
        return defaultValue.declaringJavaClass.enumConstants
            ?.firstOrNull { it.name == rawValue } as? T
            ?: defaultValue
    }

    companion object {
        private const val PREFERENCES_NAME = "ikar_kotlin_chat_settings"
        private const val DEFAULT_MESSAGE_TEXT_SIZE_SP = 18
        private const val DEFAULT_BUBBLE_CORNER_RADIUS_DP = 11
        private const val KEY_MESSAGE_TEXT_SIZE_SP = "message_text_size_sp"
        private const val KEY_BUBBLE_CORNER_RADIUS_DP = "bubble_corner_radius_dp"
        private const val KEY_SELECTED_WALLPAPER_PRESET_ID = "selected_wallpaper_preset_id"
        private const val KEY_CUSTOM_WALLPAPER_URI = "custom_wallpaper_uri"
        private const val KEY_USE_CUSTOM_WALLPAPER = "use_custom_wallpaper"
        private const val KEY_CHAT_LIST_LAYOUT = "chat_list_layout"
        private const val KEY_SWIPE_LEFT_ACTION = "swipe_left_action"
        private const val KEY_AUTO_NIGHT_THEME_ENABLED = "auto_night_theme_enabled"
        private const val KEY_IN_APP_BROWSER_ENABLED = "in_app_browser_enabled"
        private const val KEY_ANIMATIONS_ENABLED = "animations_enabled"
        private const val KEY_MEDIA_TAP_TO_BROWSE_ENABLED = "media_tap_to_browse_enabled"
        private const val KEY_RAISE_TO_LISTEN_ENABLED = "raise_to_listen_enabled"
        private const val KEY_RAISE_TO_TALK_ENABLED = "raise_to_talk_enabled"
        private const val KEY_PAUSE_MUSIC_ON_RECORD_ENABLED = "pause_music_on_record_enabled"
        private const val KEY_PAUSE_MUSIC_ON_PLAYBACK_ENABLED = "pause_music_on_playback_enabled"
        private const val KEY_DIRECT_SHARE_ENABLED = "direct_share_enabled"
        private const val KEY_SHOW_SENSITIVE_CONTENT_ENABLED = "show_sensitive_content_enabled"
        private const val KEY_SEND_BY_ENTER_ENABLED = "send_by_enter_enabled"
        private const val KEY_DISTANCE_UNIT = "distance_unit"
    }
}
