package com.optix.android.ui.screens.settings

import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.*
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.filled.Settings
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import com.optix.android.domain.model.AiProviderType
import com.optix.android.ui.components.neonTextFieldColors
import com.optix.android.ui.theme.*

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SettingsSheet(
    viewModel: SettingsViewModel = hiltViewModel(),
    onDismiss: () -> Unit,
) {
    val aiConfig by viewModel.aiConfig.collectAsState()
    var draft by remember(aiConfig) { mutableStateOf(aiConfig) }
    var providerExpanded by remember { mutableStateOf(false) }
    val tAccent = T.accent
    val tSurface = T.surface

    Column(
        modifier = Modifier
            .fillMaxWidth()
            .background(T.background)
            .verticalScroll(rememberScrollState()),
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .background(tSurface)
                .drawBehind {
                    drawLine(tAccent, Offset(0f, size.height), Offset(size.width, size.height), strokeWidth = 1f)
                }
                .padding(horizontal = 20.dp, vertical = 14.dp),
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.spacedBy(12.dp),
        ) {
            Box(
                modifier = Modifier
                    .size(32.dp)
                    .background(T.accent.copy(alpha = 0.12f), RoundedCornerShape(4.dp))
                    .border(1.dp, T.accent.copy(alpha = 0.4f), RoundedCornerShape(4.dp)),
                contentAlignment = Alignment.Center,
            ) {
                Icon(Icons.Default.Settings, contentDescription = null, tint = T.accent, modifier = Modifier.size(16.dp))
            }
            Column {
                Text("AI SETTINGS", color = T.accent, style = MaterialTheme.typography.titleMedium)
                Text("Provider & model configuration", color = T.onSurfaceMid, style = MaterialTheme.typography.labelSmall)
            }
        }

        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(horizontal = 20.dp, vertical = 16.dp),
            verticalArrangement = Arrangement.spacedBy(12.dp),
        ) {
            ExposedDropdownMenuBox(
                expanded = providerExpanded,
                onExpandedChange = { providerExpanded = it },
            ) {
                OutlinedTextField(
                    value = draft.provider.displayName,
                    onValueChange = {},
                    readOnly = true,
                    label = { Text("Provider", color = T.onSurfaceMid) },
                    trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(providerExpanded) },
                    modifier = Modifier.fillMaxWidth().menuAnchor(),
                    colors = neonTextFieldColors(),
                )
                ExposedDropdownMenu(
                    expanded = providerExpanded,
                    onDismissRequest = { providerExpanded = false },
                    modifier = Modifier.background(T.surfaceVar),
                ) {
                    AiProviderType.entries.forEach { type ->
                        DropdownMenuItem(
                            text = { Text(type.displayName, color = T.onSurface) },
                            onClick = {
                                draft = draft.copy(provider = type, model = type.defaultModel)
                                providerExpanded = false
                            },
                        )
                    }
                }
            }

            if (draft.provider != AiProviderType.OFFLINE) {
                OutlinedTextField(
                    value = draft.apiKey,
                    onValueChange = { draft = draft.copy(apiKey = it) },
                    label = { Text("API Key", color = T.onSurfaceMid) },
                    modifier = Modifier.fillMaxWidth(),
                    colors = neonTextFieldColors(),
                    visualTransformation = PasswordVisualTransformation(),
                    singleLine = true,
                )
            }

            if (draft.provider == AiProviderType.OPENROUTER) {
                OutlinedTextField(
                    value = draft.baseUrl,
                    onValueChange = { draft = draft.copy(baseUrl = it) },
                    label = { Text("Base URL", color = T.onSurfaceMid) },
                    modifier = Modifier.fillMaxWidth(),
                    colors = neonTextFieldColors(),
                    singleLine = true,
                )
            }

            if (draft.provider != AiProviderType.OFFLINE) {
                OutlinedTextField(
                    value = draft.model,
                    onValueChange = { draft = draft.copy(model = it) },
                    label = { Text("Model", color = T.onSurfaceMid) },
                    modifier = Modifier.fillMaxWidth(),
                    colors = neonTextFieldColors(),
                    singleLine = true,
                )
            }

            OutlinedTextField(
                value = draft.systemPrompt,
                onValueChange = { draft = draft.copy(systemPrompt = it) },
                label = { Text("System Prompt", color = T.onSurfaceMid) },
                modifier = Modifier.fillMaxWidth().height(100.dp),
                colors = neonTextFieldColors(),
                maxLines = 4,
                textStyle = MaterialTheme.typography.bodyMedium.copy(color = T.onSurface),
            )

            Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                Button(
                    onClick = { viewModel.saveAiConfig(draft); onDismiss() },
                    colors = ButtonDefaults.buttonColors(
                        containerColor = T.accent,
                        contentColor = if (T.isDark) Color.Black else Color.White
                    ),
                    shape = RoundedCornerShape(3.dp),
                    modifier = Modifier.weight(1f),
                ) { Text("SAVE") }
                Button(
                    onClick = onDismiss,
                    colors = ButtonDefaults.buttonColors(containerColor = T.surfaceVar, contentColor = T.onSurface),
                    shape = RoundedCornerShape(3.dp),
                    modifier = Modifier.weight(1f),
                ) { Text("CANCEL") }
            }

            Spacer(Modifier.height(8.dp))
        }
    }
}
