import APIClient
import CommentsClient
import ComposableArchitecture
import Foundation
import StatsigClient
import Utilities

extension CommentsSheetReducer {
    func handleUserCommentTextUpdated(oldValue: String, newValue: String, state: inout State) -> Effect<Action> {
        let commentWasEmpty = oldValue.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
        let isNowNonEmpty = !newValue.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty

        // Mark typing session started when user types first character
        if commentWasEmpty && isNowNonEmpty && !state.hasStartedTypingSession {
            state.hasStartedTypingSession = true
        }

        updateCommentText(newValue, state: &state)
        let commentIsEmpty = !state.hasCommentText

        lockTrackTimeIfNeeded(state: &state, when: commentWasEmpty && !commentIsEmpty)
        unlockTrackTimeIfNeeded(state: &state, when: commentIsEmpty)

        return handleMentionsProcessing(newValue, state: &state)
    }

    func handleAddSingleEmoji(_ emoji: String, state: inout State) -> Effect<Action> {
        guard state.userCommentText.count < CommentsClientV2.commentLengthLimit else {
            return .none
        }
        let commentWasEmpty = !state.hasCommentText
        state.userCommentText.append(emoji)
        lockTrackTimeIfNeeded(state: &state, when: commentWasEmpty)
        return .none
    }
}

private extension CommentsSheetReducer {
    func updateCommentText(_ text: String, state: inout State) {
        if text.count > CommentsClientV2.commentLengthLimit {
            state.userCommentText = String(text.prefix(CommentsClientV2.commentLengthLimit))
        } else {
            state.userCommentText = text
        }
    }

    func handleMentionsProcessing(_ text: String, state: inout State) -> Effect<Action> {
        // Clean up invalid mentions (remove from mentions list, but don't modify text)
        state.userMentions = state.userMentions.filter { isValidMention($0, in: text) }

        // Update mention search suggestions
        if let handle = extractCurrentMention(from: text) {
            return .run { [entityId = state.item.commentEntityId, entityType = state.item.commentEntityType] send in
                try await withTaskCancellation(id: UserMentionSearchCancellableId(), cancelInFlight: true) {
                    try await Task.sleep(for: .milliseconds(150)) // Debounce to avoid too many API calls
                    commentsSheetClient.searchForUserByHandle(handle, entityId, entityType)
                }
            }
        } else {
            state.userMentionSearchSuggestions = []
            return .none
        }
    }
}
