//
//  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("Ancien mot de passe", text: self.$oldPassword)
                    PasswordField("Nouveau mot de passe", text: self.$password1)
                    PasswordField("Confirmer du nouveau mot de passe", text: self.$password2)
                    
                    Section {
                        RowButtonView("Changer de mot de passe", role: .destructive) {
                            await self._changePassword()
                        }
                        .disabled(isLoading)
                    } footer: {
                        if self.errorMessage.count > 0 {
                            Text(self.errorMessage).foregroundStyle(.logoRed)
                        }
                    }
                }
            } else {
                VStack {
                    Text("Votre mot de passe a bien été changé")
                    RowButtonView("Ok") {
                        dismiss()
                    }
                }.padding()
            }
        }
        .navigationTitle("Changer de mot de passe")
        .navigationBarTitleDisplayMode(.inline)
        .toolbarBackground(.visible, for: .navigationBar)
    }
    
    fileprivate func _changePassword() async {
        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()
//    }
//}
