/*
 * Copyright (C) 2026 SHX VPN
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or (at your
 * option) any later version.
 */

package org.strongswan.android.ui.compose

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
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.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.Add
import androidx.compose.material.icons.rounded.Close
import androidx.compose.material.icons.rounded.Delete
import androidx.compose.material.icons.rounded.Edit
import androidx.compose.material.icons.rounded.Language
import androidx.compose.material.icons.rounded.MoreVert
import androidx.compose.material.icons.rounded.PlayArrow
import androidx.compose.material.icons.rounded.Search
import androidx.compose.material.icons.rounded.Stop
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import org.strongswan.android.R
import org.strongswan.android.data.VpnProfile
import org.strongswan.android.logic.VpnStateService.State
import org.strongswan.android.ui.compose.theme.LocalShxStatusColors
import org.strongswan.android.ui.compose.theme.ScreenPadding

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ProfilesScreen(
	state: HomeUiState,
	onConnect: (VpnProfile) -> Unit,
	onDisconnect: () -> Unit,
	onEdit: (VpnProfile) -> Unit,
	onDelete: (VpnProfile) -> Unit,
	onAdd: () -> Unit,
)
{
	var query by remember { mutableStateOf("") }
	var menuFor by remember { mutableStateOf<VpnProfile?>(null) }
	var pendingDelete by remember { mutableStateOf<VpnProfile?>(null) }
	val activeUuid = state.activeProfile?.getUUID()
	val connected = state.vpnState == State.CONNECTED
	val profiles = state.profiles
	val filtered = remember(query, profiles)
	{
		if (query.isBlank()) profiles
		else profiles.filter {
			(it.name ?: "").contains(query, ignoreCase = true) || (it.gateway ?: "").contains(query, ignoreCase = true)
		}
	}

	Column(Modifier.fillMaxSize())
	{
		TopAppBar(
			title = { Text(stringResource(R.string.nav_profiles), fontWeight = FontWeight.SemiBold) },
			actions = {
				IconButton(onClick = onAdd) {
					Icon(Icons.Rounded.Add, contentDescription = stringResource(R.string.add_profile_cta))
				}
			},
			colors = androidx.compose.material3.TopAppBarDefaults.topAppBarColors(
				containerColor = MaterialTheme.colorScheme.background,
			),
		)
		OutlinedTextField(
			value = query,
			onValueChange = { query = it },
			modifier = Modifier
				.fillMaxWidth()
				.padding(horizontal = ScreenPadding, vertical = 4.dp),
			placeholder = { Text(stringResource(R.string.search_profiles)) },
			leadingIcon = { Icon(Icons.Rounded.Search, contentDescription = null) },
			trailingIcon = {
				if (query.isNotEmpty())
				{
					IconButton(onClick = { query = "" }) {
						Icon(Icons.Rounded.Close, contentDescription = null)
					}
				}
			},
			singleLine = true,
			shape = MaterialTheme.shapes.medium,
		)
		if (filtered.isEmpty())
		{
			EmptyProfilesState(query = query, onAdd = onAdd)
		}
		else
		{
			Surface(
				shape = MaterialTheme.shapes.large,
				color = MaterialTheme.colorScheme.surfaceContainerLow,
				modifier = Modifier
					.fillMaxWidth()
					.padding(horizontal = ScreenPadding, vertical = 12.dp),
			) {
				LazyColumn {
					itemsIndexed(filtered, key = { _, p -> p.getUUID().toString() }) { index, profile ->
						val isActive = connected && profile.getUUID() == activeUuid
						Box {
							ShxProfileRow(
								profile = profile,
								active = isActive,
								onClick = { if (isActive) onDisconnect() else onConnect(profile) },
								onLongClick = { menuFor = profile },
								trailing = {
									IconButton(onClick = { menuFor = profile }) {
										Icon(
											Icons.Rounded.MoreVert,
											contentDescription = null,
											tint = MaterialTheme.colorScheme.onSurfaceVariant,
										)
									}
									if (isActive) ActiveBadge()
								},
							)
							DropdownMenu(expanded = menuFor == profile, onDismissRequest = { menuFor = null })
							{
								if (isActive)
								{
									DropdownMenuItem(
										text = { Text(stringResource(R.string.disconnect)) },
										leadingIcon = { Icon(Icons.Rounded.Stop, contentDescription = null) },
										onClick = {
											menuFor = null
											onDisconnect()
										},
									)
								}
								else
								{
									DropdownMenuItem(
										text = { Text(stringResource(R.string.connect)) },
										leadingIcon = { Icon(Icons.Rounded.PlayArrow, contentDescription = null) },
										onClick = {
											menuFor = null
											onConnect(profile)
										},
									)
								}
								DropdownMenuItem(
									text = { Text(stringResource(R.string.edit_profile)) },
									leadingIcon = { Icon(Icons.Rounded.Edit, contentDescription = null) },
									onClick = {
										menuFor = null
										onEdit(profile)
									},
								)
								DropdownMenuItem(
									text = {
										Text(
											stringResource(R.string.delete_profile),
											color = MaterialTheme.colorScheme.error,
										)
									},
									leadingIcon = {
										Icon(
											Icons.Rounded.Delete,
											contentDescription = null,
											tint = MaterialTheme.colorScheme.error,
										)
									},
									onClick = {
										menuFor = null
										pendingDelete = profile
									},
								)
							}
						}
						if (index < filtered.lastIndex)
						{
							ShxDivider()
						}
					}
				}
			}
		}
	}

	pendingDelete?.let { profile ->
		AlertDialog(
			onDismissRequest = { pendingDelete = null },
			title = { Text(stringResource(R.string.delete_profile)) },
			text = { Text(profile.name ?: "") },
			confirmButton = {
				TextButton(onClick = {
					onDelete(profile)
					pendingDelete = null
				}) { Text(stringResource(R.string.delete_profile), color = MaterialTheme.colorScheme.error) }
			},
			dismissButton = {
				TextButton(onClick = { pendingDelete = null }) {
					Text(stringResource(android.R.string.cancel))
				}
			},
		)
	}
}

@Composable
private fun EmptyProfilesState(query: String, onAdd: () -> Unit)
{
	Column(
		modifier = Modifier
			.fillMaxWidth()
			.padding(32.dp),
		horizontalAlignment = Alignment.CenterHorizontally,
		verticalArrangement = Arrangement.spacedBy(12.dp),
	)
	{
		Icon(
			Icons.Rounded.Language,
			contentDescription = null,
			tint = MaterialTheme.colorScheme.onSurfaceVariant,
			modifier = Modifier.size(48.dp),
		)
		Text(
			text = if (query.isBlank()) stringResource(R.string.no_profiles) else stringResource(R.string.nothing_found),
			style = MaterialTheme.typography.bodyLarge,
			color = MaterialTheme.colorScheme.onSurfaceVariant,
		)
		if (query.isBlank())
		{
			Spacer(Modifier.height(8.dp))
			Row {
				TextButton(onClick = onAdd) {
					Icon(Icons.Rounded.Add, contentDescription = null, modifier = Modifier.size(18.dp))
					Spacer(Modifier.size(8.dp))
					Text(stringResource(R.string.add_profile_cta))
				}
			}
		}
	}
}
