aboutsummaryrefslogtreecommitdiffstats
path: root/frontend/src/pages/Admin.tsx
blob: 776f78e231234606240983b18ef80f6385a916bf (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
import { useNavigate } from "react-router";
import { NavBar } from "../components/NavBar";
import { useAuth } from "../contexts/AuthContext";
import SessionExpiredPopup from "../components/SessionExpiredPopup";
import UnauthorizedAccess from "../components/UnauthorizedAccess";
import CollapsibleSection from "../components/admin/CollapsibleSection";
import InviteCodeManager from "../components/admin/InviteCodeManager";
import GameManager from "../components/admin/GameManager";
import UserDeletion from "../components/admin/UserDeletion";
import { useState } from "react";

interface GameFormData {
  gameInternalName: string;
  gameFormattedName: string;
  gameDescription: string;
}

interface InviteFormData {
  uses: string;
  code: string;
}

const Admin = () => {
  const { user, isLoading, logout } = useAuth();
  const [showAddGame, setShowAddGame] = useState(false);
  const [showCreateInvite, setShowCreateInvite] = useState(false);
  const [showUserDeletion, setShowUserDeletion] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [isCreatingInvite, setIsCreatingInvite] = useState(false);
  const [createdInviteCode, setCreatedInviteCode] = useState<string | null>(null);
  const navigate = useNavigate();

  const handleLogout = async () => {
    try {
      await logout();
      navigate("/");
    } catch (error) {
      console.error("Logout failed:", error);
      alert("Network error during logout. Please try again.");
    }
  };

  const handleGameSubmit = async (formData: GameFormData) => {
    setIsSubmitting(true);

    try {
      const response = await fetch(import.meta.env.VITE_API_URL + '/admin/createGame', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        credentials: 'include',
        body: JSON.stringify(formData),
      });

      if (!response.ok) {
        const error = await response.json();
        throw new Error(error.error || 'Failed to create game');
      }

      alert('Game created successfully!');
      setShowAddGame(false);

    } catch (error) {
      console.error('Failed to create game:', error);
      alert(error instanceof Error ? error.message : 'Failed to create game');
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleInviteSubmit = async (inviteFormData: InviteFormData) => {
    const uses = parseInt(inviteFormData.uses);
    if (isNaN(uses) || uses <= 0) {
      alert('Please enter a valid number of uses');
      return;
    }

    setIsCreatingInvite(true);

    try {
      const requestBody: { uses: number; code?: string } = { uses };
      if (inviteFormData.code.trim()) {
        requestBody.code = inviteFormData.code.trim();
      }

      const response = await fetch(import.meta.env.VITE_API_URL + '/admin/createInvite', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        credentials: 'include',
        body: JSON.stringify(requestBody),
      });

      if (!response.ok) {
        const error = await response.json();
        throw new Error(error.error || 'Failed to create invite code');
      }

      const result = await response.json();
      setCreatedInviteCode(result.inviteCode.code);

    } catch (error) {
      console.error('Failed to create invite code:', error);
      alert(error instanceof Error ? error.message : 'Failed to create invite code');
    } finally {
      setIsCreatingInvite(false);
    }
  };

  const handleUserDeleted = () => {
    // Optional: Add any additional logic after user deletion
    console.log('User deleted successfully');
  };

  if (isLoading) {
    return <div className="min-h-screen bg-slate-950 flex items-center justify-center">
      <div className="text-center">
        <div className="w-8 h-8 border-2 border-violet-500 border-t-transparent rounded-full animate-spin mx-auto mb-4"></div>
        <p className="text-slate-300">Loading Admin Dashboard...</p>
      </div>
    </div>;
  }

  if (!user) {
    return <SessionExpiredPopup />;
  }

  if (!user.isAdmin && user.id != 1) {
    return <UnauthorizedAccess />;
  }

  return (
    <div className="min-h-screen bg-slate-950">
      <NavBar user={user} handleLogout={handleLogout} currentPage="home"/>

      {/* Main Content */}
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <div className="mb-8">
          <h1 className="text-3xl font-bold text-white mb-2">Admin Page</h1>
          <p className="text-slate-400">
            Welcome Mirage Webmaster! Here are a variety of settings and tools you can use to customize the experience
          </p>
        </div>

        {/* Create Invite Code Section */}
        <CollapsibleSection
          title="Create Invite Code"
          isOpen={showCreateInvite}
          onToggle={() => setShowCreateInvite(!showCreateInvite)}
        >
          <InviteCodeManager
            onInviteSubmit={handleInviteSubmit}
            isCreatingInvite={isCreatingInvite}
            createdInviteCode={createdInviteCode}
          />
        </CollapsibleSection>

        {/* Add New Game Section */}
        <CollapsibleSection
          title="Add New Game"
          isOpen={showAddGame}
          onToggle={() => setShowAddGame(!showAddGame)}
        >
          <GameManager
            onGameSubmit={handleGameSubmit}
            isSubmitting={isSubmitting}
          />
        </CollapsibleSection>

        {/* User Deletion Section */}
        <CollapsibleSection
          title="Delete User"
          isOpen={showUserDeletion}
          onToggle={() => setShowUserDeletion(!showUserDeletion)}
        >
          <UserDeletion
            onUserDeleted={handleUserDeleted}
          />
        </CollapsibleSection>
      </div>
    </div>
  );
};

export default Admin;
send patches to the email below
yukais@pinapelz.com
include the subject [PATCH repo_name]
pinapelz.com
homepage