'use client'

import { Constants, EncodeStringToBase64 } from '@/app/utils'
import { Button } from '@/components/Button'
import { TextField } from '@/components/Fields'

export default function RegisterForm() {
  return (
    <form
      onSubmit={async (event) => {
        event.preventDefault()

        const response = await fetch(
          `https://${process.env.NODE_ENV === 'production' ? window.location.host : 'navilearnapi.ex.umbach.dev'}/api/v1/organization`,
          {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
            },
            body: JSON.stringify({
              email: event.currentTarget.email.value,
              password: EncodeStringToBase64(
                event.currentTarget.password.value,
              ),
            }),
          },
        )

        if (!response.ok) {
          console.error('Failed to register user!')
          return
        }

        const data = await response.json()

        // Redirect to the dashboard
        window.location.href = `https://${data.OrganizationSubdomain}${Constants.API_URL}?s=${data.Session}`
      }}
      className="mt-10 grid grid-cols-1 gap-x-6 gap-y-8 sm:grid-cols-2"
    >
      <TextField
        className="col-span-full"
        label="E-Mail"
        name="email"
        type="email"
        autoComplete="email"
        required
      />
      <TextField
        className="col-span-full"
        label="Passwort"
        name="password"
        type="password"
        autoComplete="new-password"
        required
      />

      <div className="col-span-full">
        <Button type="submit" variant="solid" color="blue" className="w-full">
          <span>Registrieren</span>
        </Button>
      </div>
    </form>
  )
}
