package com.seven.ikar.kotlin.feature.settings

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.WindowInsetsSides
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.only
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.safeDrawing
import androidx.compose.foundation.layout.windowInsetsPadding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.seven.ikar.kotlin.core.settings.AppSettingsSnapshot
import com.seven.ikar.kotlin.ui.IkarRowDivider
import com.seven.ikar.kotlin.ui.IkarScreenSurface
import com.seven.ikar.kotlin.ui.IkarSectionCard
import com.seven.ikar.kotlin.ui.IkarSectionTitle
import com.seven.ikar.kotlin.ui.IkarSimpleHeader
import com.seven.ikar.kotlin.ui.IkarToggleRow
import com.seven.ikar.kotlin.ui.IkarValueRow
import com.seven.ikar.kotlin.ui.theme.TelegramInkMuted

@Composable
fun DataStorageSettingsScreen(
    state: AppSettingsUiState,
    onBackClick: () -> Unit,
    onSnapshotChanged: ((AppSettingsSnapshot) -> AppSettingsSnapshot) -> Unit,
    onProxyClick: () -> Unit,
    onResetClick: () -> Unit
) {
    val snapshot = state.snapshot
    IkarScreenSurface(modifier = Modifier.fillMaxSize()) {
        Column(
            modifier = Modifier
                .fillMaxSize()
                .windowInsetsPadding(WindowInsets.safeDrawing.only(WindowInsetsSides.Vertical))
                .verticalScroll(rememberScrollState())
                .padding(horizontal = 18.dp, vertical = 16.dp),
            verticalArrangement = Arrangement.spacedBy(16.dp)
        ) {
            IkarSimpleHeader(title = "Данные и память", onBackClick = onBackClick)

            IkarSectionCard {
                IkarSectionTitle("Использование памяти", modifier = Modifier.padding(bottom = 12.dp))
                IkarValueRow(
                    "Кэш Ikar",
                    "Лимит локальных медиа и превью на устройстве.",
                    "${snapshot.maxCacheMb} МБ",
                    onClick = { onSnapshotChanged { it.copy(maxCacheMb = nextCacheLimit(it.maxCacheMb)) } }
                )
                IkarRowDivider(startIndent = 0.dp)
                IkarValueRow(
                    "Хранить медиа",
                    "Срок хранения локальных файлов перед LRU-очисткой.",
                    "${snapshot.keepMediaDays} дн.",
                    onClick = { onSnapshotChanged { it.copy(keepMediaDays = nextKeepDays(it.keepMediaDays)) } }
                )
                Text(
                    "Параметры сохраняются локально и готовы для подключения к TransferQueue/LRU-очистке.",
                    modifier = Modifier.padding(top = 8.dp),
                    style = MaterialTheme.typography.bodySmall,
                    color = TelegramInkMuted
                )
            }

            IkarSectionCard {
                IkarSectionTitle("Автозагрузка медиа", modifier = Modifier.padding(bottom = 12.dp))
                IkarToggleRow(
                    "Фото",
                    "Автоматически загружать фото в чатах.",
                    snapshot.autoDownloadPhotos,
                    onCheckedChange = { value -> onSnapshotChanged { it.copy(autoDownloadPhotos = value) } }
                )
                IkarRowDivider(startIndent = 0.dp)
                IkarToggleRow(
                    "Видео",
                    "Автоматически загружать видео только по Wi-Fi.",
                    snapshot.autoDownloadVideosOnWifi,
                    onCheckedChange = { value -> onSnapshotChanged { it.copy(autoDownloadVideosOnWifi = value) } }
                )
                IkarRowDivider(startIndent = 0.dp)
                IkarToggleRow(
                    "Файлы",
                    "Автозагрузка документов только по Wi-Fi.",
                    snapshot.autoDownloadFilesOnWifi,
                    onCheckedChange = { value -> onSnapshotChanged { it.copy(autoDownloadFilesOnWifi = value) } }
                )
                IkarRowDivider(startIndent = 0.dp)
                IkarToggleRow(
                    "Сохранять в галерею",
                    "Добавлять новые медиа в системную галерею.",
                    snapshot.saveMediaToGallery,
                    onCheckedChange = { value -> onSnapshotChanged { it.copy(saveMediaToGallery = value) } }
                )
            }

            IkarSectionCard {
                IkarSectionTitle("Сеть", modifier = Modifier.padding(bottom = 12.dp))
                IkarToggleRow(
                    "Меньше данных для звонков",
                    "Снижать битрейт звонков в мобильной сети.",
                    snapshot.lowDataCalls,
                    onCheckedChange = { value -> onSnapshotChanged { it.copy(lowDataCalls = value) } }
                )
                IkarRowDivider(startIndent = 0.dp)
                IkarValueRow(
                    "Прокси",
                    "SOCKS/MTProto/HTTP профиль для сетевого слоя.",
                    if (snapshot.proxyEnabled) "Вкл." else "Выкл.",
                    onClick = onProxyClick
                )
            }

            Button(onClick = onResetClick, modifier = Modifier.fillMaxWidth()) {
                Text("Сбросить настройки")
            }
            Button(onClick = onBackClick, modifier = Modifier.fillMaxWidth()) {
                Text("Готово")
            }
        }
    }
}

private fun nextCacheLimit(current: Int): Int = when {
    current < 512 -> 512
    current < 1024 -> 1024
    current < 4096 -> 4096
    else -> 128
}

private fun nextKeepDays(current: Int): Int = when {
    current < 7 -> 7
    current < 30 -> 30
    current < 90 -> 90
    current < 365 -> 365
    else -> 1
}
