/*
 * 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

import android.content.Intent
import android.os.Bundle
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.ListItem
import androidx.compose.material3.SecondaryTabRow
import androidx.compose.material3.Tab
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.strongswan.android.R
import org.strongswan.android.data.VpnProfileDataSource
import org.strongswan.android.logic.StrongSwanApplication
import org.strongswan.android.logic.TrustedCertificateManager
import org.strongswan.android.logic.TrustedCertificateManager.TrustedCertificateSource
import org.strongswan.android.security.TrustedCertificateEntry
import org.strongswan.android.ui.compose.SecondaryScaffold
import org.strongswan.android.ui.compose.theme.ShxTheme
import java.beans.PropertyChangeListener
import java.security.KeyStore

class TrustedCertificatesActivity : AppCompatActivity()
{
	companion object
	{
		const val SELECT_CERTIFICATE = "one.shx.strongswan.ext.action.SELECT_CERTIFICATE"
	}

	override fun onCreate(savedInstanceState: Bundle?)
	{
		super.onCreate(savedInstanceState)
		enableEdgeToEdge()
		val select = SELECT_CERTIFICATE == intent.action
		setContent {
			ShxTheme {
				CertificatesScreen(
					selectMode = select,
					onBack = { finish() },
					onPicked = { alias ->
						setResult(RESULT_OK, Intent().putExtra(VpnProfileDataSource.KEY_CERTIFICATE, alias))
						finish()
					},
				)
			}
		}
	}
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun CertificatesScreen(
	selectMode: Boolean,
	onBack: () -> Unit,
	onPicked: (String) -> Unit,
)
{
	val context = LocalContext.current
	val sources = remember {
		listOf(
			TrustedCertificateSource.SYSTEM to context.getString(R.string.system_tab),
			TrustedCertificateSource.USER to context.getString(R.string.user_tab),
			TrustedCertificateSource.LOCAL to context.getString(R.string.local_tab),
		)
	}
	var tab by remember { mutableIntStateOf(0) }
	var entries by remember { mutableStateOf(listOf<TrustedCertificateEntry>()) }
	var pendingDelete by remember { mutableStateOf<TrustedCertificateEntry?>(null) }
	val scope = rememberCoroutineScope()
	val allowImport = StrongSwanApplication.getInstance().managedConfigurationService.managedConfiguration.isAllowCertificateImport
	val importLauncher = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) {
		if (it.resultCode == android.app.Activity.RESULT_OK)
		{
			scope.launch { reload(sources[tab].first) { entries = it } }
		}
	}

	fun load()
	{
		scope.launch { reload(sources[tab].first) { entries = it } }
	}

	DisposableEffect(tab) {
		load()
		val observer = PropertyChangeListener { load() }
		TrustedCertificateManager.getInstance().addObserver(observer)
		onDispose { TrustedCertificateManager.getInstance().deleteObserver(observer) }
	}

	SecondaryScaffold(
		title = stringResource(R.string.trusted_certs_title),
		onBack = onBack,
		actions = {
			if (allowImport)
			{
				IconButton(onClick = {
					importLauncher.launch(Intent(context, TrustedCertificateImportActivity::class.java))
				}) { Icon(Icons.Default.Add, contentDescription = stringResource(R.string.import_certificate)) }
			}
			IconButton(onClick = {
				scope.launch {
					withContext(Dispatchers.IO) {
						TrustedCertificateManager.getInstance().reset().load()
					}
					reload(sources[tab].first) { entries = it }
				}
			}) { Icon(Icons.Default.Refresh, contentDescription = stringResource(R.string.reload_trusted_certs)) }
		},
	) { padding ->
		Column(Modifier.fillMaxSize().padding(padding)) {
			SecondaryTabRow(selectedTabIndex = tab) {
				sources.forEachIndexed { index, pair ->
					Tab(selected = tab == index, onClick = { tab = index }, text = { Text(pair.second) })
				}
			}
			LazyColumn(Modifier.fillMaxSize()) {
				items(entries, key = { it.alias }) { entry ->
					ListItem(
						headlineContent = { Text(entry.subjectPrimary) },
						supportingContent = { Text(entry.subjectSecondary.ifEmpty { entry.alias }) },
						modifier = Modifier.clickable {
							if (selectMode) onPicked(entry.alias)
							else if (sources[tab].first == TrustedCertificateSource.LOCAL) pendingDelete = entry
						},
					)
				}
			}
		}
	}

	pendingDelete?.let { entry ->
		AlertDialog(
			onDismissRequest = { pendingDelete = null },
			title = { Text(stringResource(R.string.delete_certificate_question)) },
			text = { Text(entry.subjectPrimary) },
			confirmButton = {
				TextButton(onClick = {
					try
					{
						val store = KeyStore.getInstance("LocalCertificateStore")
						store.load(null, null)
						store.deleteEntry(entry.alias)
						TrustedCertificateManager.getInstance().reset()
					}
					catch (_: Exception)
					{
					}
					pendingDelete = null
					load()
				}) { Text(stringResource(R.string.delete_profile)) }
			},
			dismissButton = {
				TextButton(onClick = { pendingDelete = null }) {
					Text(stringResource(android.R.string.cancel))
				}
			},
		)
	}
}

private suspend fun reload(source: TrustedCertificateSource, onResult: (List<TrustedCertificateEntry>) -> Unit)
{
	val list = withContext(Dispatchers.IO) {
		val manager = TrustedCertificateManager.getInstance().load()
		manager.getCACertificates(source).map { (alias, cert) -> TrustedCertificateEntry(alias, cert) }
			.sorted()
	}
	onResult(list)
}
