package com.seven.ikar.kotlin.feature.devices

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
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.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import com.seven.ikar.kotlin.core.model.UserSessionDto
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.theme.TelegramBlue
import com.seven.ikar.kotlin.ui.theme.TelegramDanger
import com.seven.ikar.kotlin.ui.theme.TelegramInkMuted

@Composable
fun DevicesScreen(
    state: DevicesUiState,
    onBackClick: () -> Unit,
    onRefreshClick: () -> Unit,
    onRevokeClick: (UserSessionDto) -> Unit
) {
    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)
            state.errorMessage?.let {
                Text(it, color = TelegramDanger, style = MaterialTheme.typography.bodySmall)
            }
            if (state.isLoading && state.sessions.isEmpty()) {
                CircularProgressIndicator(color = TelegramBlue)
            }
            IkarSectionCard {
                IkarSectionTitle("Активные сеансы", modifier = Modifier.padding(bottom = 8.dp))
                state.sessions.forEachIndexed { index, session ->
                    DeviceRow(session = session, enabled = !state.isSaving, onRevokeClick = { onRevokeClick(session) })
                    if (index != state.sessions.lastIndex) {
                        IkarRowDivider()
                    }
                }
            }
            TextButton(onClick = onRefreshClick) { Text("Обновить") }
        }
    }
}

@Composable
private fun DeviceRow(
    session: UserSessionDto,
    enabled: Boolean,
    onRevokeClick: () -> Unit
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 12.dp),
        horizontalArrangement = Arrangement.spacedBy(10.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {
        Column(modifier = Modifier.weight(1f)) {
            Text(session.deviceName, style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold)
            Text(
                text = "Последняя активность: ${session.lastSeenAt}",
                style = MaterialTheme.typography.bodySmall,
                color = TelegramInkMuted
            )
        }
        if (session.isCurrent) {
            Text("Текущий", color = TelegramBlue)
        } else {
            TextButton(enabled = enabled, onClick = onRevokeClick) { Text("Завершить") }
        }
    }
}
