package de.trainingstagebuch.app.ui.screens

import android.net.Uri
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
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.OutlinedTextField
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.saveable.rememberSaveable
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.ClubTeamItem
import de.trainingstagebuch.app.ui.ErrorBanner
import de.trainingstagebuch.app.ui.ErrorSnackbarHost
import de.trainingstagebuch.app.ui.TrainingstagebuchTopBar
import de.trainingstagebuch.app.viewmodel.TeamManagementViewModel

@Composable
fun TeamManagementScreen(
    teamManagementViewModel: TeamManagementViewModel = viewModel()
) {
    val state by teamManagementViewModel.state.collectAsState()
    val context = LocalContext.current
    val snackbarHostState = remember { SnackbarHostState() }
    var dismissedError by remember { mutableStateOf<de.trainingstagebuch.app.utils.UiText?>(null) }
    var uploadType by rememberSaveable { mutableStateOf<String?>(null) }

    var seasonId by rememberSaveable(state.selectedSeasonId) { mutableStateOf(state.selectedSeasonId.orEmpty()) }
    var teamName by rememberSaveable { mutableStateOf("") }
    var leagueId by rememberSaveable { mutableStateOf("") }
    var myTischtennisUrl by rememberSaveable { mutableStateOf("") }
    val filePickerLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.GetContent()
    ) { uri: Uri? ->
        val type = uploadType ?: return@rememberLauncherForActivityResult
        if (uri == null) return@rememberLauncherForActivityResult
        val bytes = context.contentResolver.openInputStream(uri)?.use { it.readBytes() } ?: return@rememberLauncherForActivityResult
        val fileName = uri.lastPathSegment?.substringAfterLast('/')?.ifBlank { "team-document.pdf" } ?: "team-document.pdf"
        teamManagementViewModel.uploadDocument(
            documentType = type,
            fileName = fileName,
            bytes = bytes
        )
    }

    val selectedTeam = state.teams.firstOrNull { it.id == state.selectedTeamId }
    LaunchedEffect(selectedTeam?.id) {
        if (selectedTeam != null) {
            teamName = selectedTeam.name
            leagueId = selectedTeam.leagueId.orEmpty()
        } else {
            teamName = ""
            leagueId = ""
        }
    }

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

    Scaffold(
        topBar = { TrainingstagebuchTopBar(title = stringResource(R.string.team_management_title)) },
        snackbarHost = { ErrorSnackbarHost(hostState = snackbarHostState) }
    ) { paddingValues ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
                .padding(16.dp)
        ) {
            Text(
                text = stringResource(R.string.team_management_title),
                style = MaterialTheme.typography.headlineSmall
            )

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

            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(top = 10.dp),
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.spacedBy(8.dp)
            ) {
                OutlinedTextField(
                    value = seasonId,
                    onValueChange = { seasonId = it },
                    label = { Text(stringResource(R.string.team_management_season_id)) },
                    modifier = Modifier.weight(1f),
                    singleLine = true
                )
                OutlinedButton(onClick = {
                    teamManagementViewModel.setSeasonId(seasonId.ifBlank { null })
                }) {
                    Text(stringResource(R.string.team_management_apply_season))
                }
            }

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

            OutlinedTextField(
                value = teamName,
                onValueChange = { teamName = it },
                label = { Text(stringResource(R.string.team_management_name_label)) },
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(top = 12.dp),
                singleLine = true
            )
            OutlinedTextField(
                value = leagueId,
                onValueChange = { leagueId = it },
                label = { Text(stringResource(R.string.team_management_league_id_label)) },
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(top = 8.dp),
                singleLine = true
            )

            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(top = 10.dp),
                horizontalArrangement = Arrangement.spacedBy(8.dp)
            ) {
                Button(
                    onClick = { teamManagementViewModel.saveTeam(teamName, leagueId.ifBlank { null }) },
                    enabled = !state.actionLoading
                ) {
                    Text(stringResource(R.string.team_management_save_team))
                }
                OutlinedButton(
                    onClick = { teamManagementViewModel.deleteSelectedTeam() },
                    enabled = !state.actionLoading && selectedTeam != null
                ) {
                    Text(stringResource(R.string.club_settings_delete_button))
                }
            }

            Text(
                text = stringResource(R.string.team_management_teams_title, state.teams.size),
                style = MaterialTheme.typography.titleMedium,
                modifier = Modifier.padding(top = 14.dp, bottom = 8.dp)
            )
            if (state.teams.isEmpty()) {
                Text(
                    text = stringResource(R.string.team_management_empty_teams),
                    style = MaterialTheme.typography.bodyMedium,
                    modifier = Modifier.padding(bottom = 8.dp)
                )
            }

            LazyColumn(
                modifier = Modifier
                    .fillMaxWidth()
                    .weight(1f)
            ) {
                items(state.teams, key = { it.id }) { team ->
                    TeamRow(
                        team = team,
                        selected = team.id == state.selectedTeamId,
                        onSelect = { teamManagementViewModel.selectTeam(team.id) }
                    )
                }
            }

            if (selectedTeam != null) {
                Text(
                    text = stringResource(R.string.team_management_documents_title),
                    style = MaterialTheme.typography.titleMedium,
                    modifier = Modifier.padding(top = 10.dp)
                )
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(top = 6.dp),
                    horizontalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    OutlinedButton(
                        onClick = {
                            uploadType = "code_list"
                            filePickerLauncher.launch("*/*")
                        },
                        enabled = !state.actionLoading
                    ) {
                        Text(stringResource(R.string.team_management_upload_code_list))
                    }
                    OutlinedButton(
                        onClick = {
                            uploadType = "pin_list"
                            filePickerLauncher.launch("*/*")
                        },
                        enabled = !state.actionLoading
                    ) {
                        Text(stringResource(R.string.team_management_upload_pin_list))
                    }
                }
                if (state.documents.isEmpty()) {
                    Text(stringResource(R.string.team_management_no_documents))
                } else {
                    state.documents.forEach { doc ->
                        Row(
                            modifier = Modifier.fillMaxWidth(),
                            horizontalArrangement = Arrangement.SpaceBetween,
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            Text(doc.fileName ?: doc.id, modifier = Modifier.weight(1f))
                            OutlinedButton(
                                onClick = { teamManagementViewModel.parseDocument(doc.id) },
                                enabled = !state.actionLoading && !selectedTeam.leagueId.isNullOrBlank()
                            ) {
                                Text(stringResource(R.string.team_management_parse_document))
                            }
                        }
                    }
                }

                Text(
                    text = stringResource(R.string.team_management_mytischtennis_title),
                    style = MaterialTheme.typography.titleMedium,
                    modifier = Modifier.padding(top = 10.dp)
                )
                OutlinedTextField(
                    value = myTischtennisUrl,
                    onValueChange = { myTischtennisUrl = it },
                    label = { Text(stringResource(R.string.team_management_mytischtennis_url_label)) },
                    modifier = Modifier.fillMaxWidth(),
                    singleLine = true
                )
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(top = 8.dp),
                    horizontalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    OutlinedButton(
                        onClick = { teamManagementViewModel.parseMyTischtennisUrl(myTischtennisUrl) },
                        enabled = !state.actionLoading
                    ) {
                        Text(stringResource(R.string.team_management_parse_url))
                    }
                    OutlinedButton(
                        onClick = { teamManagementViewModel.configureMyTischtennisForSelectedTeam() },
                        enabled = !state.actionLoading && selectedTeam.id.isNotBlank()
                    ) {
                        Text(stringResource(R.string.team_management_configure_team))
                    }
                    OutlinedButton(
                        onClick = { teamManagementViewModel.configureMyTischtennisLeague() },
                        enabled = !state.actionLoading
                    ) {
                        Text(stringResource(R.string.team_management_configure_league))
                    }
                    OutlinedButton(
                        onClick = { teamManagementViewModel.fetchTeamData() },
                        enabled = !state.actionLoading
                    ) {
                        Text(stringResource(R.string.team_management_fetch_data))
                    }
                }

                if (state.playerStats.isNotEmpty()) {
                    Text(
                        text = stringResource(R.string.team_management_player_stats_title),
                        style = MaterialTheme.typography.titleMedium,
                        modifier = Modifier.padding(top = 10.dp)
                    )
                    state.playerStats.take(8).forEach { stat ->
                        Text(
                            text = stringResource(
                                R.string.team_management_player_stats_line,
                                stat.firstName,
                                stat.lastName,
                                stat.totalSeason
                            ),
                            style = MaterialTheme.typography.bodySmall
                        )
                    }
                }
            }
        }
    }
}

@Composable
private fun TeamRow(team: ClubTeamItem, selected: Boolean, onSelect: () -> Unit) {
    OutlinedButton(
        onClick = onSelect,
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 3.dp)
    ) {
        Column(modifier = Modifier.fillMaxWidth()) {
            Text(
                text = team.name,
                style = if (selected) MaterialTheme.typography.titleSmall else MaterialTheme.typography.bodyMedium
            )
            Text(
                text = stringResource(
                    R.string.team_management_team_row_meta,
                    team.leagueName ?: "-",
                    team.seasonName ?: "-"
                ),
                style = MaterialTheme.typography.bodySmall
            )
        }
    }
}
