//
//  LoginView.swift
//  PadelClub
//
//  Created by Laurent Morvillier on 19/02/2024.
//

import SwiftUI
import LeStorage

struct LoginView: View {
    
    @EnvironmentObject var dataStore: DataStore
    @EnvironmentObject var networkMonitor: NetworkMonitor

    @State var username: String = ""
    @State var password: String = ""
    @State var isLoading: Bool = false
    
    @State var showEmailPopup: Bool = false
    @State var showUserCreationForm: Bool = false
    @State var showEmailValidationMessage: Bool = false
    @State var showSubscriptionView: Bool = false

    @State var errorText: String? = nil
    
    var loginFailed: Binding<Bool> {
        Binding {
            errorText != nil
        } set: { newValue in
            if newValue == false {
                errorText = nil
            }
        }
    }
    
    var handler: (User) -> ()
    
    var body: some View {
        
        Form {
            
            Section {
                TextField("Nom d'utilisateur", text: self.$username)
                    .autocorrectionDisabled()
                    .textInputAutocapitalization(.never)
                SecureField("Mot de passe", text: self.$password)

            } header: {
                if self.showEmailValidationMessage {
                    Text("Vous pouvez maintenant ouvrir votre boîte mail pour valider votre compte. Vous pourrez ensuite vous connecter ici.")
                }
            }
            
            Section {
                RowButtonView("Connexion") {
                    await self._login()
                }
//                if let error = self.errorText {
//                    Text(error).font(.callout).foregroundStyle(.red)
//                }
            }
            
            if !self.showEmailValidationMessage {
                Section {
                    Button(action: {
                        self.showUserCreationForm = true
                    }, label: {
                        Text("Créer un compte")
                    })
                    .sheet(isPresented: self.$showUserCreationForm) {
                        UserCreationFormView(isPresented: self.$showUserCreationForm, showEmailValidationMessage: self.$showEmailValidationMessage)
                    }

                    
//                    NavigationLink("Créer un compte") {
//                        UserCreationView()
//                    }
                    Button(action: {
                        self.showEmailPopup = true
                    }, label: {
                        Text("Mot passe oublié")
                    })
                    .alert(
                        Text("Changer de mot de passe")
                        ,
                        isPresented: self.$showEmailPopup
                    ) {
                        EmailConfirmationView()
                    } message: {
                        Text("Veuillez entrer votre email")
                    }
                }
            }
            
        }
        .alert("Un problème est survenu", isPresented: loginFailed) {
            Button("OK") {
            }
        } message: {
            let message = [networkMonitor.connected == false ? "L'appareil n'est pas connecté à internet." as String? : nil, errorText].compacted().joined(separator: "\n")
            Text(message)
        }
        .navigationTitle("Connexion")
        .onAppear {
            #if DEBUG
            if let username = PListReader.readString(plist: "local", key: "username") {
                self.username = username
            }
            if let password = PListReader.readString(plist: "local", key: "password") {
                self.password = password
            }
            #endif
        }
    }
    
    fileprivate func _login() async {
        self.errorText = nil // reset error
        self.isLoading = true
        do {
            let service = try Store.main.service()
            let user: User = try await service.login(
                username: self.username,
                password: self.password)
            self.dataStore.user = user
            self.isLoading = false
            self.handler(user)
        } catch {
            self.isLoading = false
            self.errorText = ErrorUtils.message(error: error)
            Logger.error(error)
        }
    }
    
}

struct EmailConfirmationView: View {
    
    @State var email: String = ""
    @State var errorMessage: String = ""
    
    var body: some View {
        VStack {
            TextField("Email", text: self.$email)
                .keyboardType(.emailAddress)
            Button {
                self._forgottenPassword()
            } label: {
                Text("Envoyer l'email")
            }

        }
    }
    
    fileprivate func _forgottenPassword() {
        
        Task {
            do {
                let service = try Store.main.service()
                try await service.forgotPassword(email: self.email)
            } catch {
                Logger.error(error)
                self.errorMessage = ErrorUtils.message(error: error)
            }
        }
    }
    
}

//#Preview {
//    NavigationStack {
//        LoginView(handler: { _ in })
//    }
//}

//#Preview {
//    EmailConfirmationView()
//}
