package de.trainingstagebuch.app.ui.screens

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.TextButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
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.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import de.trainingstagebuch.app.R
import de.trainingstagebuch.app.repository.PermissionMemberItem
import de.trainingstagebuch.app.repository.PermissionResourceItem
import de.trainingstagebuch.app.ui.ErrorBanner
import de.trainingstagebuch.app.ui.ErrorSnackbarHost
import de.trainingstagebuch.app.ui.TrainingstagebuchTopBar
import de.trainingstagebuch.app.viewmodel.PermissionsViewModel

@Composable
fun PermissionsScreen(
    permissionsViewModel: PermissionsViewModel = viewModel()
) {
    val state by permissionsViewModel.state.collectAsState()
    val context = LocalContext.current
    val snackbarHostState = remember { SnackbarHostState() }
    var dismissedError by remember { mutableStateOf<de.trainingstagebuch.app.utils.UiText?>(null) }

    LaunchedEffect(state.errorMessage, state.successMessage) {
        state.errorMessage?.let {
            dismissedError = null
            snackbarHostState.showSnackbar(it.resolve(context))
        }
        state.successMessage?.let {
            snackbarHostState.showSnackbar(it.resolve(context))
        }
    }

    Scaffold(
        topBar = { TrainingstagebuchTopBar(title = stringResource(R.string.permissions_title)) },
        snackbarHost = { ErrorSnackbarHost(hostState = snackbarHostState) }
    ) { paddingValues ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
                .padding(16.dp)
        ) {
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = stringResource(R.string.permissions_title),
                    style = MaterialTheme.typography.headlineSmall
                )
                OutlinedButton(onClick = { permissionsViewModel.load(force = true) }) {
                    Text(stringResource(R.string.home_retry))
                }
            }

            val currentError = state.errorMessage
            if (currentError != null && currentError != dismissedError) {
                ErrorBanner(
                    message = currentError.resolve(context),
                    onDismiss = { dismissedError = currentError },
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(top = 10.dp)
                )
            }

            if (state.loading) {
                Column(
                    modifier = Modifier
                        .fillMaxSize()
                        .padding(top = 24.dp),
                    horizontalAlignment = Alignment.CenterHorizontally,
                    verticalArrangement = Arrangement.Center
                ) {
                    CircularProgressIndicator()
                    Text(
                        text = stringResource(R.string.permissions_loading),
                        modifier = Modifier.padding(top = 10.dp)
                    )
                }
                return@Column
            }

            if (state.roles.isNotEmpty()) {
                Text(
                    text = stringResource(R.string.permissions_roles_available),
                    style = MaterialTheme.typography.titleMedium,
                    modifier = Modifier.padding(top = 12.dp, bottom = 6.dp)
                )
                Text(
                    text = state.roles.joinToString(" | ") { role -> role.label },
                    style = MaterialTheme.typography.bodySmall
                )
            }

            Text(
                text = stringResource(R.string.permissions_members_title),
                style = MaterialTheme.typography.titleMedium,
                modifier = Modifier.padding(top = 16.dp, bottom = 8.dp)
            )

            if (state.members.isEmpty()) {
                Text(text = stringResource(R.string.permissions_members_empty))
            } else {
                LazyColumn(modifier = Modifier.fillMaxSize()) {
                    items(state.members, key = { it.userId }) { member ->
                        MemberRow(
                            member = member,
                            roleLabels = state.roles.associate { it.value to it.label },
                            onToggleStatus = { permissionsViewModel.toggleStatus(member) },
                            onChangeRole = { role -> permissionsViewModel.updateRole(member, role) },
                            onEditPermissions = { permissionsViewModel.openPermissionEditor(member) }
                        )
                    }
                }
            }
        }

        state.selectedMember?.let { member ->
            PermissionEditorDialog(
                member = member,
                structure = state.structure,
                editorValues = state.permissionEditor,
                onToggle = permissionsViewModel::togglePermission,
                onResetResource = permissionsViewModel::resetResource,
                onDismiss = permissionsViewModel::closePermissionEditor,
                onSave = permissionsViewModel::saveCustomPermissions
            )
        }
    }
}

@Composable
private fun MemberRow(
    member: PermissionMemberItem,
    roleLabels: Map<String, String>,
    onToggleStatus: () -> Unit,
    onChangeRole: (String) -> Unit,
    onEditPermissions: () -> Unit
) {
    var roleMenuOpen by remember { mutableStateOf(false) }
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 6.dp)
    ) {
        Text(text = member.email ?: member.userId, style = MaterialTheme.typography.bodyMedium)
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.spacedBy(8.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            RolePicker(
                role = member.role,
                roleLabels = roleLabels,
                expanded = roleMenuOpen,
                onExpandedChange = { roleMenuOpen = it },
                onRoleSelected = {
                    roleMenuOpen = false
                    onChangeRole(it)
                },
                enabled = !member.isOwner
            )
            Button(
                onClick = onToggleStatus,
                enabled = !member.isOwner
            ) {
                Text(if (member.approved) stringResource(R.string.permissions_active) else stringResource(R.string.permissions_inactive))
            }
            OutlinedButton(
                onClick = onEditPermissions,
                enabled = !member.isOwner
            ) {
                Text(stringResource(R.string.permissions_customize))
            }
        }
    }
}

@Composable
private fun RolePicker(
    role: String,
    roleLabels: Map<String, String>,
    expanded: Boolean,
    onExpandedChange: (Boolean) -> Unit,
    onRoleSelected: (String) -> Unit,
    enabled: Boolean
) {
    Column {
        OutlinedButton(onClick = { onExpandedChange(!expanded) }, enabled = enabled) {
            Text(roleLabels[role] ?: role)
        }
        DropdownMenu(expanded = expanded, onDismissRequest = { onExpandedChange(false) }) {
            roleLabels.forEach { (value, label) ->
                DropdownMenuItem(
                    text = { Text(label) },
                    onClick = { onRoleSelected(value) }
                )
            }
        }
    }
}

@Composable
private fun PermissionEditorDialog(
    member: PermissionMemberItem,
    structure: Map<String, PermissionResourceItem>,
    editorValues: Map<String, Map<String, Boolean?>>,
    onToggle: (String, String) -> Unit,
    onResetResource: (String) -> Unit,
    onDismiss: () -> Unit,
    onSave: () -> Unit
) {
    AlertDialog(
        onDismissRequest = onDismiss,
        title = {
            Text(
                text = stringResource(
                    R.string.permissions_dialog_title,
                    member.email ?: member.userId
                )
            )
        },
        text = {
            LazyColumn {
                structure.forEach { (resourceKey, resource) ->
                    item(key = "${resourceKey}_title") {
                        Row(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(top = 8.dp),
                            horizontalArrangement = Arrangement.SpaceBetween
                        ) {
                            Text(resource.label, style = MaterialTheme.typography.titleSmall)
                            TextButton(onClick = { onResetResource(resourceKey) }) {
                                Text(stringResource(R.string.permissions_reset))
                            }
                        }
                    }
                    items(resource.actions, key = { action -> "${resourceKey}_$action" }) { action ->
                        val value = editorValues[resourceKey]?.get(action)
                        val stateText = when (value) {
                            null -> stringResource(R.string.permissions_inherit)
                            true -> stringResource(R.string.permissions_allow)
                            false -> stringResource(R.string.permissions_deny)
                        }
                        OutlinedButton(
                            onClick = { onToggle(resourceKey, action) },
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(vertical = 2.dp)
                        ) {
                            Text(
                                stringResource(
                                    R.string.permissions_action_state,
                                    action,
                                    stateText
                                )
                            )
                        }
                    }
                }
            }
        },
        confirmButton = {
            Button(onClick = onSave) { Text(stringResource(R.string.permissions_save)) }
        },
        dismissButton = {
            OutlinedButton(onClick = onDismiss) { Text(stringResource(R.string.club_settings_cancel_button)) }
        }
    )
}
