package com.aiwazian.messenger.ui

import androidx.compose.foundation.background
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.verticalScroll
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.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.outlined.ArrowBack
import androidx.compose.material.icons.outlined.Add
import androidx.compose.material.icons.outlined.ArrowForward
import androidx.compose.material.icons.outlined.ArrowBack
import androidx.compose.material.icons.outlined.Delete
import androidx.compose.material.icons.outlined.MoreVert
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
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.Modifier
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.aiwazian.messenger.data.KanbanColumn
import com.aiwazian.messenger.data.NavigationIcon
import com.aiwazian.messenger.ui.element.PageTopBar
import com.aiwazian.messenger.viewModels.KanbanViewModel
import com.aiwazian.messenger.viewModels.NavigationViewModel

@Composable
fun KanbanScreen() {
    val navigation = viewModel<NavigationViewModel>()
    val kanban = viewModel<KanbanViewModel>()
    val boards by kanban.boards.collectAsState()
    var newBoard by remember { mutableStateOf(false) }
    var newColumnBoardId by remember { mutableStateOf<Int?>(null) }
    var renameBoardId by remember { mutableStateOf<Int?>(null) }

    Scaffold(
        topBar = {
            PageTopBar(
                title = { Text("Канбан-доски") },
                navigationIcon = NavigationIcon(Icons.AutoMirrored.Outlined.ArrowBack) { navigation.removeLastScreenInStack() }
            )
        },
        floatingActionButton = {
            FloatingActionButton(onClick = { newBoard = true }) { Icon(Icons.Outlined.Add, null) }
        }
    ) { padding ->
        Column(
            Modifier.fillMaxSize().padding(padding).verticalScroll(rememberScrollState()).padding(12.dp),
            verticalArrangement = Arrangement.spacedBy(16.dp)
        ) {
            if (boards.isEmpty()) Text("Создайте первую доску")
            boards.forEach { board ->
                Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
                    Row(verticalAlignment = androidx.compose.ui.Alignment.CenterVertically) {
                        Text(board.title, style = MaterialTheme.typography.titleLarge, modifier = Modifier.weight(1f))
                        var menu by remember { mutableStateOf(false) }
                        IconButton(onClick = { menu = true }) { Icon(Icons.Outlined.MoreVert, "Управление") }
                        DropdownMenu(expanded = menu, onDismissRequest = { menu = false }) {
                            DropdownMenuItem(
                                text = { Text("Переименовать") },
                                onClick = { menu = false; renameBoardId = board.id }
                            )
                            DropdownMenuItem(
                                text = { Text("Удалить") },
                                onClick = { menu = false; kanban.deleteBoard(board.id) }
                            )
                        }
                    }
                    Row(
                        Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()),
                        horizontalArrangement = Arrangement.spacedBy(10.dp)
                    ) {
                        board.columns.forEachIndexed { index, column ->
                            KanbanColumnCard(
                                column = column,
                                previousColumnId = board.columns.getOrNull(index - 1)?.id,
                                nextColumnId = board.columns.getOrNull(index + 1)?.id,
                                kanban = kanban
                            )
                        }
                        Button(onClick = { newColumnBoardId = board.id }) {
                            Text("Добавить колонку")
                        }
                    }
                }
            }
        }
    }

    if (newBoard) NameDialog("Новая доска", { newBoard = false }) {
        kanban.createBoard(it)
        newBoard = false
    }
    newColumnBoardId?.let { boardId ->
        NameDialog("Новая колонка", { newColumnBoardId = null }) {
            kanban.createColumn(boardId, it)
            newColumnBoardId = null
        }
    }
    renameBoardId?.let { boardId ->
        NameDialog("Название доски", { renameBoardId = null }) {
            kanban.renameBoard(boardId, it)
            renameBoardId = null
        }
    }
}

@Composable
private fun KanbanColumnCard(
    column: KanbanColumn,
    previousColumnId: Int?,
    nextColumnId: Int?,
    kanban: KanbanViewModel
) {
    var addTask by remember { mutableStateOf(false) }
    Card(Modifier.width(270.dp)) {
        Column(
            Modifier.padding(12.dp),
            verticalArrangement = Arrangement.spacedBy(8.dp)
        ) {
            Text(column.title, style = MaterialTheme.typography.titleMedium)
            column.tasks.forEach { task ->
                Card(Modifier.fillMaxWidth()) {
                    Column(Modifier.padding(10.dp)) {
                        Text(task.title)
                        if (!task.description.isNullOrBlank()) Text(task.description, style = MaterialTheme.typography.bodySmall)
                        Row {
                            if (previousColumnId != null) {
                                IconButton(onClick = { kanban.moveTask(task.id, previousColumnId) }) {
                                    Icon(Icons.Outlined.ArrowBack, "Переместить назад")
                                }
                            }
                            if (nextColumnId != null) {
                                IconButton(onClick = { kanban.moveTask(task.id, nextColumnId) }) {
                                    Icon(Icons.Outlined.ArrowForward, "Переместить")
                                }
                            }
                            IconButton(onClick = { kanban.deleteTask(task.id) }) {
                                Icon(Icons.Outlined.Delete, "Удалить")
                            }
                        }
                    }
                }
            }
            Button(onClick = { addTask = true }, modifier = Modifier.fillMaxWidth()) {
                Text("Добавить задачу")
            }
        }
    }
    if (addTask) NameDialog("Новая задача", { addTask = false }) {
        kanban.createTask(column.id, it)
        addTask = false
    }
}

@Composable
private fun NameDialog(title: String, dismiss: () -> Unit, submit: (String) -> Unit) {
    var value by remember { mutableStateOf("") }
    AlertDialog(
        onDismissRequest = dismiss,
        title = { Text(title) },
        text = { OutlinedTextField(value, { value = it }, label = { Text("Название") }) },
        confirmButton = { TextButton(onClick = { if (value.isNotBlank()) submit(value.trim()) }) { Text("Создать") } },
        dismissButton = { TextButton(onClick = dismiss) { Text("Отмена") } }
    )
}
