//
//  LoginView.swift
//  iosApp
//
//  Created by Coach Roebuck on 8/5/23.
//  Copyright © 2023 orgName. All rights reserved.
//

import SwiftUI
import shared

struct LoginView: View {
    @ObservedObject var viewModel: SwiftLoginViewModel
    @ObservedObject var navigationSelectionStore: SelectionStore
    var selectionStore: SelectionStore
    @State private var email: String = ""
    @State private var progress: Double = 0.5
    @State private var errorExists: Bool = false
    @State private var showActionSheet = true
        
    var body: some View {
        NavigationView {
            VStack(alignment: .leading) {
                loginContent

                // Invisible NavigationLinks
                NavigationLink(destination: RegisterView(selectionStore: navigationSelectionStore).customBackButton(navigationSelectionStore: navigationSelectionStore), tag: "Register", selection: $navigationSelectionStore.selection) { EmptyView() }
                NavigationLink(destination: ActivateRequestView(selectionStore: navigationSelectionStore).customBackButton(navigationSelectionStore: navigationSelectionStore), tag: "Activate", selection: $navigationSelectionStore.selection) { EmptyView() }
            }
            .background(Color(.systemBackground))
            .edgesIgnoringSafeArea(.bottom)
        }
    }
    
    var loginContent: some View {
        VStack(alignment: .leading) {
            Text(LocalizedStringKey("login_text"))
                .font(.title2)
                .fontWeight(.bold)
                .padding(EdgeInsets(top: 16, leading: 16, bottom: 16, trailing: 16))
            
            TextField(LocalizedStringKey("enter_user_name_text"), text: $email)
                .padding(8)
                .overlay(RoundedRectangle(cornerRadius: 8).stroke((self.viewModel.errorMessage.wrappedValue != nil) ? Color.red : Color.gray, lineWidth: 1))
                .padding(EdgeInsets(top: 0, leading: 16, bottom: 0, trailing: 16))
                .keyboardType(.emailAddress)
                .onChange(of: self.email) { newValue in
                    self.viewModel.viewModel.emit(loginViewModelIntent: LoginViewModelStore.IntentEmailChanged(email: newValue))
                }
            
            HStack (spacing:8) {
                if let errorMessage = self.viewModel.errorMessage.wrappedValue {
                    if(errorMessage == "ACCOUNT_PENDING") {
                        LoginFailureActionSheet
                    } else {
                        Text(LocalizedStringKey(errorMessage.description.lowercased()))
                            .foregroundColor(.red)
                    }
                }
                
                Spacer()
                
                if (self.viewModel.isInProgressEnabled.wrappedValue) {
                    CircularProgressView(progress: $progress, text: LocalizedStringKey("logging_in"))
                        .frame(width: 100, height: 100)
                } else {
                    Button () {
                        self.viewModel.viewModel.emit(loginViewModelIntent: LoginViewModelStore.IntentLoginClicked.shared)
                    } label: {
                        Text(LocalizedStringKey("login_text"))
                        .imageScale(.large)
                        .padding(.horizontal,16)
                        .padding(.vertical,10)
                        .background (
                            Capsule()
                            .stroke(Color.gray, lineWidth: 1.25)
                        )
                        .foregroundColor(.white)
                        .cornerRadius(8)
                    }
                    .padding(.horizontal,16)
                    .frame(maxWidth: .infinity, alignment: .trailing)
                    .accentColor(.white)
                    .disabled(!self.viewModel.isLoginEnabled.wrappedValue)
                }
            }
            
            Text(LocalizedStringKey("dont_have_an_account"))
                .padding(EdgeInsets(top: 8, leading: 16, bottom: 8, trailing: 16))
                .frame(maxWidth: .infinity, alignment: .center)

            Text(LocalizedStringKey("create_account_text"))
                .foregroundColor(.blue)
                .frame(maxWidth: .infinity, alignment: .center)
                .onTapGesture {
                    self.viewModel.viewModel.emit(loginViewModelIntent: LoginViewModelStore.IntentRegisterClicked.shared)
                }
            Spacer()
        }
    }
    
    var LoginFailureActionSheet: some View {
        VStack(alignment: .leading) {
        }.actionSheet(isPresented: $showActionSheet) {
            ActionSheet(
                title: Text("Verification Failed"),
                message: Text(LocalizedStringKey(self.viewModel.errorMessage.wrappedValue!.description.lowercased())).foregroundColor(.red),
                buttons: [
                    .default(Text("Activate Account"), action: {
                        self.viewModel.viewModel.emit(loginViewModelIntent: LoginViewModelStore.IntentActivateClicked.shared)
                    }),
                    .default(Text("Create a New Account"), action: {
                        self.viewModel.viewModel.emit(loginViewModelIntent: LoginViewModelStore.IntentRegisterClicked.shared)
                    }),
                    .default(Text("Login"), action: {
                        self.viewModel.viewModel.emit(loginViewModelIntent: LoginViewModelStore.IntentLoginClicked.shared)
                    }),
                ]
            )
        }
    }
    
    init(selectionStore: SelectionStore) {
        let navigationSelectionStore = SelectionStore()
        let navigator = DefaultLoginNavigator(selectionStore: selectionStore)
        let viewModdel = LoginActivityInjection.shared.inject(navigator: navigator)
        
        self.viewModel = SwiftLoginViewModel(viewModel: viewModdel)
        self.selectionStore = selectionStore
        self.navigationSelectionStore = navigationSelectionStore
        collect()
        
    }
    
    private func collect() {
        viewModel.viewModel.cFlow.collect(function: { latestState in
            print("new state=[\(String(describing: latestState))]")
            onStateReceived(latestState: latestState as! LoginViewModelStore.State)
        }, completionHandler: { error in
            print("LoginView: error=[\(String(describing: error))]")
        })
    }
    
    private func onStateReceived(latestState: LoginViewModelStore.State) {
        if let _ = latestState as? LoginViewModelStore.StateCurrentState {
            onCurrentState(latestState: latestState as! LoginViewModelStore.StateCurrentState)
        } else if let _ = latestState as? LoginViewModelStore.StateIdle {
            onIdle()
        }
    }
    
    private func onCurrentState(latestState: LoginViewModelStore.StateCurrentState) {
        self.viewModel.state = latestState
        
        DispatchQueue.main.async {
            print("updated state[\(self.viewModel.state)]")
        }
    }
    
    private func onIdle() {
        
    }
}

extension View {
    func customBackButton(navigationSelectionStore: SelectionStore) -> some View {
        self.modifier(CustomBackButtonModifier(navigationSelectionStore: navigationSelectionStore))
    }
}

struct LoginView_Previews: PreviewProvider {
    static var previews: some View {
        LoginView(selectionStore: SelectionStore())
    }
}
