---
import Layout from 'layouts/PageLayout.astro';
//import Layout from 'layouts/Layout.astro';
import AstroUtils from 'libs/AstroUtils';
import { getEnv } from 'libs/Env';
import ContactUs from 'components/widgets/Contact.astro';
import Oauth from 'components/Oauth.astro';

const pb = Astro.locals.pb

if(pb.authStore.isValid){
    return Astro.redirect("/account")
}

let loged = false

await AstroUtils.wrap(async () => {
    if (Astro.request.method !== 'POST'){
        return
    }
    const form = await Astro.request.formData()
    const request = {
        username: form.get("username") as string,
        name: form.get("name") as string,
        email: form.get("email") as string,
        password: form.get("password") as string,
        passwordConfirm: form.get("passwordConfirm") as string,
    }
    try{
        await pb.collection('users').create(request)
        loged = true
      }catch(e){
        console.log(e);
      }
    })
if (loged) {
  return Astro.redirect('/account/login')
}

const metadata = {
  title: 'Register',
  ignoreTitleTemplate: true,
};
---

<Layout metadata={metadata}>

  <ContactUs
    formid='account-creation'
    title='Inscription'
    subtitle="inscrivez vous pour sauvegardez vos recherche"
    button='Créer un compte'
    method='post'
    enctype="multipart/form-data"
    inputs={[
      {
        type: 'text',
        name: 'name',
        label: 'Prénom Nom',
        placeholder: "Michel Biche"
      },{
        type: 'text',
        name: 'username',
        label: 'Nom d\'utilisateur',
        placeholder: "michel85"
      },{
        type: 'email',
        name: 'email',
        label: 'Adresse email',
        placeholder: "michel@example.com"
      },{
        type: 'password',
        name: 'password',
        label: 'Créez un mot de passe',
      },{
        type: 'password',
        name: 'passwordConfirm',
        label: 'Confirmer votre mot de passe',
      },
    ]}
  />
  <Oauth/>
</Layout>
