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

import SwiftUI
import LeStorage

struct ChangePasswordView: View {
    
    @State var oldPassword: String = ""
    @State var password1: String = ""
    @State var password2: String = ""
    
    @State var isLoading: Bool = false
    @State var errorMessage: String = ""
    
    var body: some View {
        
        Form {
            
            SecureField("Old password", text: self.$oldPassword)
            SecureField("Password", text: self.$password1)
            SecureField("Password again", text: self.$password2)

            Section {
                Button(action: {
                    self._changePassword()
                }, label: {
                    Text("Changer de mot de passe")
                })
                .frame(maxWidth: .infinity)
            } footer: {
                if self.errorMessage.count > 0 {
                    Text(self.errorMessage).foregroundStyle(.red)
                }
            }
        }
        .navigationTitle("Changer de mot de passe")
    }
    
    fileprivate func _changePassword() {
        Task {
            do {
                self.isLoading = true
                let service = try Store.main.service()
                _ = try await service.changePassword(
                    oldPassword: self.oldPassword,
                    password1: self.password1,
                    password2: self.password2)
                self.isLoading = false
            } catch {
                Logger.error(error)
                self.errorMessage = ErrorUtils.message(error: error)
            }
        }
        
    }
    
}

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