//
//  UserCreationView.swift
//  PadelClub
//
//  Created by Laurent Morvillier on 13/02/2024.
//

import SwiftUI
import LeStorage

struct UserCreationFormView: View {
    
    @EnvironmentObject var networkMonitor: NetworkMonitor

    @Binding var isPresented: Bool
    @Binding var showEmailValidationMessage: Bool

//    @Binding var showLoginScreen: Bool

    @State var username: String = ""
    @State var password1: String = ""
    @State var password2: String = ""
    @State var email: String = ""
    
    @State var firstName: String = ""
    @State var lastName: String = ""
    @State var phone: String = ""
    
    @State var showAlertView = false
    @State var alertMessage: String = "" {
        didSet {
            self.showAlertView = true
            self.isLoading = false
        }
    }
    
    @State var selectedCountryIndex = 0

    @State var dataCollectAuthorized: Bool = false
    
    let countries: [String] = Locale.countries()
    
    @State var isLoading = false
    
    var body: some View {
        
        NavigationStack {
            Form {
                
                Section {
                    TextField("Nom d'utilisateur", text: self.$username)
                        .autocorrectionDisabled()
                        .textInputAutocapitalization(.never)
                    TextField("Email", text: self.$email)
                        .keyboardType(.emailAddress)
                        .textInputAutocapitalization(.never)
                }
                
                Section {
                    SecureField("Mot de passe", text: self.$password1)
                    SecureField("Confirmez le mot de passe", text: self.$password2)
                }
                
                Section {
                    TextField("Prénom", text: self.$firstName)
                        .autocorrectionDisabled()
                    TextField("Nom", text: self.$lastName)
                        .autocorrectionDisabled()
                    TextField("Téléphone", text: self.$phone)
                        .autocorrectionDisabled()
                    
                    LabeledContent {
                        Picker(selection: $selectedCountryIndex) {
                            ForEach(0..<self.countries.count, id: \.self) { index in
                                Text(self.countries[index]).tag(index)
                            }
                        } label: {
                            
                        }
                    } label: {
                        Text("Pays")
                    }

                }

                Section {
                    Toggle(isOn: self.$dataCollectAuthorized) {
                        Text("J'autorise XLR Sport, éditeur de Padel Club, à sauvegarder les données ci-dessus. XLR Sport s'engage à ne pas partager ces données.").font(.footnote)
                    }
                }
                
                Section {
                    RowButtonView("Créer votre compte") {
                        await self._create()
                    }
                    .disabled(!self.dataCollectAuthorized)
                }
            }.navigationTitle("Créez votre compte")
        }
        .onAppear {
            self._selectCountry()
        }
        .alert(self.alertMessage, isPresented: self.$showAlertView, actions: {
            Button("Ok", action: {})
        } )
    }
    
    fileprivate func _selectCountry() {
        guard let regionCode = Locale.current.region?.identifier, let country = Locale.current.localizedString(forRegionCode: regionCode) else {
            return
        }
        
        self.selectedCountryIndex = self.countries.firstIndex(of: country) ?? 0
    }
    
    fileprivate func _create() async {
        guard networkMonitor.connected == true else {
            self.alertMessage = "L'appareil n'est pas connecté à internet."
            return
        }
        
        self.isLoading = true
        self.username = self.username.trimmed
        self.firstName = self.firstName.trimmed
        self.lastName = self.lastName.trimmed
        self.email = self.email.trimmed

        guard self.password1 == self.password2 else {
            self.alertMessage = "Les mots de passe ne correspondent pas"
            return
        }
        
        guard username.count > 2 else {
            self.alertMessage = "Veuillez renseigner au moins 3 caractères pour votre nom d'utilisateur"
            return
        }
        
        guard self.email.isValidEmail() else {
            self.alertMessage = "L'adresse email n'est pas valide"
            return
        }
        
        guard firstName.count > 0 else {
            self.alertMessage = "Votre prénom ne peut pas être vide"
            return
        }
        
        guard lastName.count > 0 else {
            self.alertMessage = "Votre nom ne peut pas être vide"
            return
        }
        
        do {
            let country: String = self.countries[self.selectedCountryIndex]
            let userCreationForm: UserCreationForm = UserCreationForm(
                user: DataStore.shared.user, // local user
                username: self.username,
                password: self.password1,
                firstName: self.firstName,
                lastName: self.lastName,
                email: self.email,
                phone: self.phone,
                country: country)
            
            let service: Services = try Store.main.service()
            let _: User = try await service.createAccount(user: userCreationForm)
            
            DispatchQueue.main.async {
                self.isLoading = false
                self.showEmailValidationMessage = true
                self.isPresented = false
            }
            
        } catch {
            self.isLoading = false
            self.alertMessage = ErrorUtils.message(error: error)
            Logger.error(error)
        }
    }
    
}

//#Preview {
//    UserCreationFormView(isPresented: .constant(true), showEmailValidationMessage: .constant(true))
//}
