package de.tsschulz.tt_tagebuch.app.ui

import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Delete
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import cafe.adriel.voyager.core.screen.Screen
import cafe.adriel.voyager.koin.getScreenModel
import cafe.adriel.voyager.navigator.LocalNavigator
import de.tsschulz.tt_tagebuch.app.viewmodel.MemberEditScreenModel
import de.tsschulz.tt_tagebuch.app.viewmodel.MemberEditState
import de.tsschulz.tt_tagebuch.shared.models.Member
import de.tsschulz.tt_tagebuch.shared.models.MemberContact

class MemberEditScreen(private val clubId: Int, private val member: Member? = null) : Screen {
    @Composable
    override fun Content() {
        val navigator = LocalNavigator.current
        val viewModel = getScreenModel<MemberEditScreenModel>()
        val state by viewModel.state.collectAsState()

        var firstName by remember { mutableStateOf(member?.firstName ?: "") }
        var lastName by remember { mutableStateOf(member?.lastName ?: "") }
        var birthDate by remember { mutableStateOf(member?.birthDate ?: "") }
        var gender by remember { mutableStateOf(member?.gender ?: "unknown") }
        var active by remember { mutableStateOf(member?.active ?: true) }
        var testMembership by remember { mutableStateOf(member?.testMembership ?: true) }
        var contacts by remember { mutableStateOf<List<MemberContact>>(member?.contacts?.toMutableList() ?: mutableListOf<MemberContact>()) }

        Scaffold(
            topBar = {
                TopAppBar(
                    title = { Text(if (member == null) "Neues Mitglied" else "Mitglied bearbeiten") },
                    navigationIcon = {
                        IconButton(onClick = { navigator?.pop() }) {
                            Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back")
                        }
                    },
                    actions = {
                        TextButton(onClick = {
                            val newMember = Member(
                                id = member?.id ?: 0,
                                firstName = firstName,
                                lastName = lastName,
                                clubId = clubId,
                                active = active,
                                birthDate = birthDate,
                                gender = gender,
                                testMembership = testMembership,
                                contacts = contacts
                            )
                            viewModel.saveMember(clubId, newMember)
                        }, enabled = state !is MemberEditState.Saving) {
                            Text("Speichern", color = Color.White)
                        }
                    }
                )
            }
        ) { padding ->
            if (state is MemberEditState.Saving) {
                LinearProgressIndicator(modifier = Modifier.fillMaxWidth())
            }

            Column(
                modifier = Modifier
                    .padding(padding)
                    .fillMaxSize()
                    .verticalScroll(rememberScrollState())
                    .padding(16.dp)
            ) {
                Text("Stammdaten", style = MaterialTheme.typography.h6)
                TextField(
                    value = firstName,
                    onValueChange = { firstName = it },
                    label = { Text("Vorname") },
                    modifier = Modifier.fillMaxWidth()
                )
                Spacer(Modifier.height(8.dp))
                TextField(
                    value = lastName,
                    onValueChange = { lastName = it },
                    label = { Text("Nachname") },
                    modifier = Modifier.fillMaxWidth()
                )
                Spacer(Modifier.height(8.dp))
                TextField(
                    value = birthDate,
                    onValueChange = { birthDate = it },
                    label = { Text("Geburtsdatum (YYYY-MM-DD)") },
                    modifier = Modifier.fillMaxWidth()
                )
                
                Spacer(Modifier.height(16.dp))
                Text("Status", style = MaterialTheme.typography.h6)
                Row(verticalAlignment = Alignment.CenterVertically) {
                    Checkbox(checked = active, onCheckedChange = { active = it })
                    Text("Aktiv")
                    Spacer(Modifier.width(16.dp))
                    Checkbox(checked = testMembership, onCheckedChange = { testMembership = it })
                    Text("Probetraining")
                }

                Spacer(Modifier.height(24.dp))
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceBetween,
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Text("Kontakte", style = MaterialTheme.typography.h6)
                    IconButton(onClick = {
                        contacts = (contacts + MemberContact(type = "phone", value = "")).toMutableList()
                    }) {
                        Icon(Icons.Default.Add, contentDescription = "Add Contact")
                    }
                }

                contacts.forEachIndexed { index, contact ->
                    Row(
                        modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp),
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        TextField(
                            value = contact.value,
                            onValueChange = { newValue ->
                                val newList = contacts.toMutableList()
                                newList[index] = contact.copy(value = newValue)
                                contacts = newList
                            },
                            label = { Text(if (contact.type == "phone") "Telefon" else "Email") },
                            modifier = Modifier.weight(1f)
                        )
                        IconButton(onClick = {
                            val newList = contacts.toMutableList()
                            newList.removeAt(index)
                            contacts = newList
                        }) {
                            Icon(Icons.Default.Delete, contentDescription = "Remove")
                        }
                    }
                }
            }

            LaunchedEffect(state) {
                if (state is MemberEditState.Success) {
                    navigator?.pop()
                }
            }
        }
    }
}
