import SwiftUI

struct ConversationButton: View {
    @EnvironmentObject var userService: UserService
    var postId: Int
    var parentCommentId: Int? = nil
    var hasComments: Bool

    @State private var awaitingLoginForComment: Bool = false
    @State private var presentCommentSheet: Bool = false
    
    var body: some View {
        Button(action: conversationButtonAction) {
            Text(conversationButtonTitle)
        }
        .buttonStyle(PrimaryButtonStyle())
        .onChange(of: userService.signedInState) { newValue in
            if case .signedIn = newValue, awaitingLoginForComment {
                awaitingLoginForComment = false
                presentCommentSheet = true
            }
        }
        .sheet(isPresented: $presentCommentSheet) {
            AddCommentView(postId: postId, parentCommentId: parentCommentId)
        }
    }
    
    private var conversationButtonTitle: String {
        if case .signedIn = userService.signedInState {
            
            if parentCommentId != nil {
                return "Reply to comment"
            } else
            if !hasComments {
                return "Start the conversation"
            } else {
                return "Join the conversation"
            }
            
        } else {
            if parentCommentId != nil {
                return "Sign in to reply"
            } else
            if !hasComments {
                return "Sign in to start the conversation"
            } else {
                return "Sign in to join the conversation"
            }
        }
    }
    
    private func conversationButtonAction() {
        if case .signedIn = userService.signedInState {
            presentCommentSheet = true
        } else {
            awaitingLoginForComment = true
            userService.signInWithViewController()
        }
    }
}
