"use client"; import { User } from "@/api/gen/idb/user/v1/user_pb"; import { ChangeEventHandler, FormEventHandler, MouseEventHandler, useEffect, useState } from "react"; import { RequestBody as VerifyRequestBody, ResponseBody as VerifyResponseBody, } from "@/app/api/new-user/verify-username/types"; import { RequestBody as SubmitRequestBody, ResponseBody as SubmitResponseBody, } from "@/app/api/new-user/add-ibd-creds/types"; import styles from "./styles.module.css"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { faSpinner } from "@fortawesome/free-solid-svg-icons"; export default function NewUserForm() { const [username, setUsername] = useState(""); const [password, setPassword] = useState(""); const [isUsernameValid, setIsUsernameValid] = useState(false); const [isSubmittingUsername, setIsSubmittingUsername] = useState(false); const [isSubmittingForm, setIsSubmittingForm] = useState(false); const [isCheckingCreds, setIsCheckingCreds] = useState(false); const [error, setError] = useState(null); const handleUsernameSubmit: FormEventHandler = (e) => { e.preventDefault(); setIsSubmittingUsername(true); setError(null); const body: VerifyRequestBody = { username }; fetch("/api/new-user/verify-username", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify(body), }).then((res) => res.json()) .then((data) => { const { exists } = VerifyResponseBody.parse(data); if (exists) { setIsUsernameValid(true); } else { setError("Username does not exist"); } setIsSubmittingUsername(false); }); }; const handleFormSubmit: FormEventHandler = (e) => { e.preventDefault(); setIsSubmittingForm(true); setError(null); const body: SubmitRequestBody = { username, password }; fetch("/api/new-user/add-ibd-creds", { method: "PUT", headers: { "Content-Type": "application/json", }, body: JSON.stringify(body), }).then((res) => res.json()) .then((data) => { const {} = SubmitResponseBody.parse(data); setIsSubmittingForm(false); setIsCheckingCreds(true); return fetch("/api/new-user/check-ibd-creds", { method: "PUT", }); }) .then((res) => { if (res.status === 200) { window.location.href = "/dashboard"; } else { setError("Invalid credentials"); setIsCheckingCreds(false); } }); }; const handleBack: MouseEventHandler = () => { setIsUsernameValid(false); setPassword(""); setError(null); }; return (

Set Up Your Account

setUsername(e.target.value)} className={`w-full px-3 py-2 mt-1 border ${ isUsernameValid ? "border-gray-300 bg-gray-200" : "border-gray-300" } rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500`} required disabled={isUsernameValid} /> {error && !isUsernameValid && (

{error}

)}
{!isUsernameValid && (
)}
{isUsernameValid && (
setPassword(e.target.value)} className="w-full px-3 py-2 mt-1 border border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500" required />
{error && isUsernameValid && (

{error}

)}
)}
); }