Files
peworkshop/app/(main)/create-team/page.js

207 lines
5.8 KiB
JavaScript

"use client";
import { useState, useEffect } from "react";
import { useSession } from "next-auth/react";
import { useRouter } from "next/navigation";
import Link from "next/link";
export default function CreateTeam() {
const { data: session, status, update: updateSession } = useSession();
const [teamName, setTeamName] = useState("");
const [error, setError] = useState("");
const [isLoading, setIsLoading] = useState(true);
const [success, setSuccess] = useState(false);
const router = useRouter();
useEffect(() => {
if (status === "authenticated") {
if (session?.user?.teamId) {
router.push(`/${session.user.teamId}`);
} else {
setIsLoading(false);
}
} else if (status === "unauthenticated") {
router.push("/login");
}
}, [status, session, router]);
const handleCreateTeam = async (e) => {
e.preventDefault();
setIsLoading(true);
setError("");
try {
// Validate team name
if (!teamName || teamName.trim() === "") {
throw new Error("Team name is required");
}
// Check session status before proceeding
if (status !== "authenticated") {
throw new Error("You must be logged in to create a team");
}
const response = await fetch("/api/teams/create", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
credentials: "include", // Important: include credentials with the request
body: JSON.stringify({ name: teamName.trim() }),
});
const data = await response.json();
if (!response.ok) {
throw new Error(data.error || "Failed to create team");
}
console.log("Team created successfully with ID:", data.teamId);
setSuccess(true);
// Try to update the session with the new team ID
try {
// Wait briefly to ensure DB changes are reflected
await new Promise((resolve) => setTimeout(resolve, 500));
await updateSession(); // Update the NextAuth session if possible
} catch (sessionErr) {
console.warn(
"Session update failed, using redirect instead:",
sessionErr
);
}
// Use window.location for a hard navigation to ensure session is fully updated
setTimeout(() => {
window.location.href = `/${data.teamId}`;
}, 1000);
} catch (err) {
console.error("Team creation error:", err);
setError(err.message);
} finally {
setIsLoading(false);
}
};
if (isLoading && !success) {
return <div className="loading">Loading...</div>;
}
return (
<div className="auth-page">
<div className="page-header">
<div className="back-button"></div>
<div className="page-title">Create Team</div>
<div className="placeholder"></div>
</div>
<div className="auth-container">
<div className="auth-card">
{success ? (
<div className="success-message">
<div className="success-icon">✅</div>
<h2>Team Created Successfully!</h2>
<p>Redirecting to your new team page...</p>
</div>
) : (
<>
<h1>Create a New Team</h1>
<form onSubmit={handleCreateTeam}>
<div className="form-group">
<input
type="text"
placeholder="Team Name"
value={teamName}
onChange={(e) => setTeamName(e.target.value)}
required
className="auth-input"
maxLength={50}
/>
</div>
<button
type="submit"
className="auth-button"
disabled={isLoading}
>
{isLoading ? "Creating..." : "Create Team"}
</button>
</form>
{error && <p className="error-message">{error}</p>}
</>
)}
<div className="team-options">
<Link href="/team-selection">
<button className="auth-button secondary-button">
Back to Team Selection
</button>
</Link>
</div>
</div>
</div>
<style jsx>{`
.auth-page {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
height: 100vh;
overflow: hidden;
}
.auth-container {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
width: 100%;
max-width: 400px;
padding: 20px;
box-sizing: border-box;
}
.auth-card {
width: 100%;
padding: 20px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
border-radius: 8px;
background-color: #fff;
}
.form-group {
margin-bottom: 10px;
}
.auth-input {
width: 100%;
padding: 10px;
border: 1px solid #ccc;
border-radius: 4px;
}
.auth-button {
width: 100%;
padding: 10px;
margin-top: 10px;
background-color: #68543c; /* Updated brown color */
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
text-align: center;
}
.error-message {
color: red;
margin-top: 10px;
}
.success-message {
text-align: center;
padding: 20px 0;
}
.success-icon {
font-size: 48px;
margin-bottom: 10px;
color: #4caf50;
}
.secondary-button {
background-color: #a98467;
}
`}</style>
</div>
);
}