/*
 * Copyright (c) 2025 Element Creations Ltd.
 * Copyright 2023-2025 New Vector Ltd.
 *
 * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial.
 * Please see LICENSE files in the repository root for full details.
 */

package id.databisnis.android.bachot.features.roomdetails.impl.members.details

import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.produceState
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import dev.zacsweers.metro.Assisted
import dev.zacsweers.metro.AssistedInject
import id.databisnis.android.bachot.features.userprofile.api.UserProfileEvents
import id.databisnis.android.bachot.features.userprofile.api.UserProfilePresenterFactory
import id.databisnis.android.bachot.features.userprofile.api.UserProfileState
import id.databisnis.android.bachot.features.userprofile.api.UserProfileVerificationState
import id.databisnis.android.bachot.libraries.androidutils.clipboard.ClipboardHelper
import id.databisnis.android.bachot.libraries.architecture.Presenter
import id.databisnis.android.bachot.libraries.designsystem.utils.snackbar.LocalSnackbarDispatcher
import id.databisnis.android.bachot.libraries.designsystem.utils.snackbar.SnackbarMessage
import id.databisnis.android.bachot.libraries.designsystem.utils.snackbar.collectSnackbarMessageAsState
import id.databisnis.android.bachot.libraries.matrix.api.core.UserId
import id.databisnis.android.bachot.libraries.matrix.api.encryption.EncryptionService
import id.databisnis.android.bachot.libraries.matrix.api.encryption.identity.IdentityState
import id.databisnis.android.bachot.libraries.matrix.api.encryption.identity.IdentityStateChange
import id.databisnis.android.bachot.libraries.matrix.api.room.JoinedRoom
import id.databisnis.android.bachot.libraries.matrix.ui.room.getRoomMemberAsState
import id.databisnis.android.bachot.libraries.matrix.ui.room.roomMemberIdentityStateChange
import id.databisnis.android.bachot.libraries.ui.strings.CommonStrings
import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch

/**
 * Presenter for room member details screen.
 * Rely on UserProfilePresenter, but override some fields with room member info when available.
 */
@AssistedInject
class RoomMemberDetailsPresenter(
    @Assisted private val roomMemberId: UserId,
    private val room: JoinedRoom,
    private val encryptionService: EncryptionService,
    private val clipboardHelper: ClipboardHelper,
    userProfilePresenterFactory: UserProfilePresenterFactory,
) : Presenter<UserProfileState> {
    interface Factory {
        fun create(roomMemberId: UserId): RoomMemberDetailsPresenter
    }

    private val userProfilePresenter = userProfilePresenterFactory.create(roomMemberId)

    @Composable
    override fun present(): UserProfileState {
        val coroutineScope = rememberCoroutineScope()

        val snackbarDispatcher = LocalSnackbarDispatcher.current
        val snackbarMessage by snackbarDispatcher.collectSnackbarMessageAsState()
        val roomMember by room.getRoomMemberAsState(roomMemberId)
        LaunchedEffect(Unit) {
            // Update room member info when opening this screen
            // We don't need to assign the result as it will be automatically propagated by `room.getRoomMemberAsState`
            room.getUpdatedMember(roomMemberId)
        }

        val roomUserName: String? by produceState(
            initialValue = roomMember?.displayName,
            key1 = roomMember,
        ) {
            value = room.userDisplayName(roomMemberId).getOrNull() ?: roomMember?.displayName
        }

        val roomUserAvatar: String? by produceState(
            initialValue = roomMember?.avatarUrl,
            key1 = roomMember,
        ) {
            value = room.userAvatarUrl(roomMemberId).getOrNull() ?: roomMember?.avatarUrl
        }

        val userProfileState = userProfilePresenter.present()

        val identityStateChanges = produceState<IdentityStateChange?>(initialValue = null) {
            // Fetch the initial identity state manually
            val identityState = encryptionService.getUserIdentity(roomMemberId).getOrNull()
            value = identityState?.let { IdentityStateChange(roomMemberId, it) }

            // Subscribe to the identity changes
            room.roomMemberIdentityStateChange(waitForEncryption = false)
                .map { it.find { it.identityRoomMember.userId == roomMemberId } }
                .map { roomMemberIdentityStateChange ->
                    // If we didn't receive any info, manually fetch it
                    roomMemberIdentityStateChange?.identityState ?: encryptionService.getUserIdentity(roomMemberId).getOrNull()
                }
                .filterNotNull()
                .collect { value = IdentityStateChange(roomMemberId, it) }
        }

        val verificationState by remember {
            derivedStateOf {
                when (identityStateChanges.value?.identityState) {
                    IdentityState.VerificationViolation -> UserProfileVerificationState.VERIFICATION_VIOLATION
                    IdentityState.Verified -> UserProfileVerificationState.VERIFIED
                    IdentityState.Pinned, IdentityState.PinViolation -> UserProfileVerificationState.UNVERIFIED
                    else -> UserProfileVerificationState.UNKNOWN
                }
            }
        }

        fun handleEvent(event: UserProfileEvents) {
            when (event) {
                UserProfileEvents.WithdrawVerification -> coroutineScope.launch {
                    encryptionService.withdrawVerification(roomMemberId)
                }
                is UserProfileEvents.CopyToClipboard -> {
                    clipboardHelper.copyPlainText(event.text)
                    snackbarDispatcher.post(SnackbarMessage(CommonStrings.common_copied_to_clipboard))
                }
                else -> userProfileState.eventSink(event)
            }
        }

        return userProfileState.copy(
            userName = roomUserName ?: userProfileState.userName,
            avatarUrl = roomUserAvatar ?: userProfileState.avatarUrl,
            verificationState = verificationState,
            snackbarMessage = snackbarMessage,
            eventSink = ::handleEvent,
        )
    }
}
