import BasicField from "@/components/form/basicField";
import { FormEvent, useState } from "react";
import Router from 'next/router'

const Register = () => {
  const [username, setUsername] = useState<string>("");
  const [email, setEmail] = useState<string>("");
  const [password, setPassword] = useState<string>("");
  const [passwordConfirmation, setPasswordConfirmation] = useState<string>("");
  const [error, setError] = useState<string>("");

  const handleSubmit = async (event: FormEvent) => {
    event.preventDefault()

    const JSONdata = JSON.stringify({
      username: username,
      email: email,
      password: password,
      profile: ""
    })
    const endpoint = `${process.env.NEXT_PUBLIC_USER_SERVICE_URL}api/register`
    const options = {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSONdata,
    }
    const response = await fetch(endpoint, options)
    const result = await response.json()

    if(result.error !== undefined){
      setError(result.error.error)
    } else {
      if(result.token !== undefined && result.username !== undefined){
        sessionStorage.setItem('username', result.username)
        sessionStorage.setItem('token', result.token) 
        Router.push("/feed")
      } 
    }
  }

 return (
    <>
      <div className="flex min-h-full items-center justify-center px-4 py-12 sm:px-6 lg:px-8">
       
        <div className="w-full max-w-md space-y-2">
            <h2 className="mt-6 text-center text-3xl font-bold tracking-tight text-gray-900">
              Create an account
            </h2>
            <p className=" text-center text-sm text-gray-600">
              Or{' '}
              <a href="/signIn" className="font-medium text-c-pink hover:text-indigo-500">
                log in
              </a>
            </p>

          <form className="mt-8 space-y-6"  onSubmit={(e) => handleSubmit(e)}>
            <input type="hidden" name="remember" defaultValue="true" />
            <div className="rounded-md shadow-sm">
              <BasicField name="username" placeholder="Username" onChange={setUsername}/>
              <BasicField name="email" placeholder="Email Address" onChange={setEmail}/>
              <BasicField name="password" placeholder="Password" onChange={setPassword}/>
              <BasicField name="password" placeholder="Confirm Password" onChange={setPasswordConfirmation} error={password === passwordConfirmation ? null : "Confirmation doesn't match"}/>
            </div>
            <div>
              <p className="text-xs text-c-pink m-2">
                {error}
              </p>
              <button
                type="submit"
                className="group relative flex w-full justify-center rounded-md bg-c-pink px-3 py-2 text-sm font-semibold text-white hover:bg-c-pink hover:text-c-green hover:border-c-pink focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-c-pink"
              >
                Sign in
              </button>
            </div>
          </form>
        </div>
      </div>
    </>
  )
}

export default Register;