import APIClient
import CommentsClient
import ComponentLibrary
import ComposableArchitecture
import StatsigClient
import Utilities

extension CommentsSheetReducer {
    func handleUserMentionSearch(state: inout State) -> Effect<Action> {
        let commentWasEmpty = !state.hasCommentText
        if state.userCommentText.isEmpty || state.userCommentText.last == " " {
            state.userCommentText += "@"
        } else {
            state.userCommentText += " @"
        }
        lockTrackTimeIfNeeded(state: &state, when: commentWasEmpty)
        return .none
    }

    func handleUserMentionSearchItemTapped(_ user: SimpleProfile, state: inout State) -> Effect<Action> {
        let oldValue = state.userCommentText
        let updatedCommentText = replacePendingMention(
            from: oldValue,
            for: user,
            mentions: &state.userMentions
        )
        return .send(.onUserCommentTextUpdated(oldValue: oldValue, newValue: updatedCommentText))
    }
}

extension CommentsSheetReducer {
    func isValidMention(_ mention: CommentUserMention, in text: String) -> Bool {
        InteractiveTextFormatter.isValidMention(mention, in: text)
    }

    /// Finds the @mention currently being typed at the end of text
    func extractCurrentMention(from text: String) -> String? {
        InteractiveTextFormatter.extractCurrentMention(from: text)
    }

    /// Replaces @mention with user's display name and updates mentions list
    private func replacePendingMention(
        from text: String,
        for user: SimpleProfile,
        mentions: inout [CommentUserMention]
    ) -> String {
        InteractiveTextFormatter.replacePendingMention(
            from: text,
            for: user,
            mentions: &mentions
        ) { start, end, handle, displayName in
            CommentUserMention(start: start, end: end, handle: handle, displayName: displayName)
        }
    }
}
