package ru.forbion.f7cloud.feature.f7support

import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.lifecycle.viewmodel.compose.viewModel
import ru.forbion.f7cloud.core.auth.AuthSession
import ru.forbion.f7cloud.core.designsystem.F7Colors
import ru.forbion.f7cloud.core.designsystem.F7ModuleScreen
import ru.forbion.f7cloud.core.designsystem.F7OverlayDismissHandler

@Composable
fun SupportScreen(
    session: AuthSession,
    modifier: Modifier = Modifier,
    createRequest: Int = 0,
    openTicketNumber: String? = null,
    onOpenTicketConsumed: () -> Unit = {},
    onUnauthorized: () -> Unit = {},
) {
    val vm: SupportViewModel = viewModel()
    val state by vm.state.collectAsState()
    val snackbarHostState = remember { SnackbarHostState() }
    val context = LocalContext.current

    val pickCreateFilesLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.OpenMultipleDocuments(),
    ) { uris ->
        if (uris.isNotEmpty()) {
            vm.addCreateFiles(context, uris)
        }
    }
    val pickChatFilesLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.OpenMultipleDocuments(),
    ) { uris ->
        if (uris.isNotEmpty()) {
            vm.addChatFiles(context, uris)
        }
    }

    LaunchedEffect(session.serverUrl, session.username) {
        vm.load(session)
    }
    LaunchedEffect(createRequest) {
        if (createRequest > 0) {
            vm.setShowCreate(true)
        }
    }
    LaunchedEffect(openTicketNumber) {
        if (!openTicketNumber.isNullOrBlank()) {
            vm.openTicketFromPush(session, openTicketNumber)
            onOpenTicketConsumed()
        }
    }
    LaunchedEffect(state.unauthorized) {
        if (state.unauthorized) onUnauthorized()
    }
    LaunchedEffect(state.snackbar) {
        val msg = state.snackbar ?: return@LaunchedEffect
        snackbarHostState.showSnackbar(msg)
        vm.clearSnackbar()
    }
    LaunchedEffect(state.error) {
        val err = state.error ?: return@LaunchedEffect
        if (state.selectedTicket != null || state.showCreate || state.showComplaint) {
            snackbarHostState.showSnackbar(err)
            vm.clearError()
        }
    }

    F7OverlayDismissHandler(
        enabled = state.showComplaint,
        onDismiss = { vm.setShowComplaint(false) },
    )
    F7OverlayDismissHandler(
        enabled = state.selectedTicket != null,
        onDismiss = { vm.closeTicket(session) },
    )
    F7OverlayDismissHandler(
        enabled = state.showCreate,
        onDismiss = { vm.setShowCreate(false) },
    )

    if (state.showCreate) {
        SupportCreateDialog(
            loading = state.loading,
            pendingFiles = state.createPendingFiles,
            onDismiss = { vm.setShowCreate(false) },
            onPickFiles = { pickCreateFilesLauncher.launch(arrayOf("*/*")) },
            onRemoveFile = vm::removeCreateFile,
            onSubmit = { subject, body -> vm.createTicket(session, subject, body) },
        )
    }

    state.selectedTicket?.let { ticket ->
        SupportChatDialog(
            session = session,
            ticket = ticket,
            messages = state.messages,
            loading = state.loading && state.messages.isEmpty(),
            sending = state.sending,
            pendingFiles = state.chatPendingFiles,
            downloadingAttachmentId = state.downloadingAttachmentId,
            onDismiss = { vm.closeTicket(session) },
            onSend = { text -> vm.sendMessage(session, text) },
            onPickFiles = { pickChatFilesLauncher.launch(arrayOf("*/*")) },
            onRemoveFile = vm::removeChatFile,
            onAttachmentClick = { vm.downloadAttachment(context, it) },
            onComplaintClick = { vm.setShowComplaint(true) },
        )
    }

    if (state.showComplaint && state.selectedTicket != null) {
        SupportComplaintDialog(
            sending = state.complaintSending,
            onDismiss = { vm.setShowComplaint(false) },
            onSubmit = { vm.submitComplaint(it) },
        )
    }

    Box(modifier = modifier.fillMaxSize()) {
        F7ModuleScreen(
            modifier = Modifier.fillMaxSize(),
            loading = state.loading && state.tickets.isEmpty() && state.selectedTicket == null,
            error = if (state.selectedTicket == null) state.error else null,
            onRefresh = { vm.load(session) },
        ) {
            if (state.selectedTicket == null) {
                SupportHomeContent(
                    serverUrl = session.serverUrl,
                    isSupportAdmin = state.config?.isSupportAdmin == true,
                    ticketsByBucket = state.ticketsByBucket,
                    hasTickets = state.hasTickets,
                    onCreateClick = { vm.setShowCreate(true) },
                    onTicketClick = { vm.openTicket(session, it) },
                    modifier = Modifier.fillMaxSize(),
                )
            }
        }
        SnackbarHost(
            hostState = snackbarHostState,
            modifier = Modifier.align(Alignment.BottomCenter),
        )
        if (state.loading && state.tickets.isNotEmpty() && state.selectedTicket == null && !state.showCreate) {
            CircularProgressIndicator(
                modifier = Modifier.align(Alignment.TopCenter),
                color = F7Colors.Primary,
            )
        }
    }
}
