//
//  ChangePasswordView.swift
//  PadelClub
//
//  Created by Laurent Morvillier on 21/02/2024.
//

import SwiftUI
import LeStorage

struct ChangePasswordView: View {
    
    @Environment(\.dismiss) var dismiss

    @State var oldPassword: String = ""
    @State var password1: String = ""
    @State var password2: String = ""
    
    @State var isLoading: Bool = false
    
    @State var errorMessage: String = ""
    
    @State var showForm: Bool = true
    
    var body: some View {
        
        Group {
            if self.showForm {
                
                Form {
                    
                    PasswordField("Old password", text: self.$oldPassword)
                    PasswordField("Password", text: self.$password1)
                    PasswordField("Password again", text: self.$password2)
                    
                    Section {
                        Button(action: {
                            self._changePassword()
                        }, label: {
                            if self.isLoading {
                                Text("Changer de mot de passe")
                            } else {
                                ProgressView()
                            }
                        })
                        .frame(maxWidth: .infinity)
                    } footer: {
                        if self.errorMessage.count > 0 {
                            Text(self.errorMessage).foregroundStyle(.red)
                        }
                    }
                }
            } else {
                VStack {
                    Text("Votre mot de passe a bien été changé")
                    RowButtonView("Ok") {
                        dismiss()
                    }
                }.padding()
            }
        }
        .navigationTitle("Changer de mot de passe")
    }
    
    fileprivate func _changePassword() {
        Task {
            do {
                self.isLoading = true
                let service = try StoreCenter.main.service()
                _ = try await service.changePassword(
                    oldPassword: self.oldPassword,
                    password1: self.password1,
                    password2: self.password2)
                self.isLoading = false
                self.showForm = false
            } catch {
                Logger.error(error)
                self.errorMessage = ErrorUtils.message(error: error)
                self.isLoading = false
            }
        }
        
    }
    
}

//#Preview {
//    NavigationStack {
//        ChangePasswordView()
//    }
//}
