Files
MemeStudio/app/(dashboard)/levels/page.tsx
2026-04-19 14:28:36 +08:00

174 lines
4.8 KiB
TypeScript

'use client'
import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { Button } from '@/components/ui/button'
import { Header } from '@/components/layout/header'
import { LevelTable } from '@/components/levels/level-table'
import { LevelDialog } from '@/components/levels/level-dialog'
import { Spinner } from '@/components/ui/spinner'
import { Level, LevelFormData } from '@/types'
import { Plus } from 'lucide-react'
import { apiFetch } from '@/lib/api'
export default function LevelsPage() {
const queryClient = useQueryClient()
const [isDialogOpen, setIsDialogOpen] = useState(false)
const [editingLevel, setEditingLevel] = useState<Level | null>(null)
const [deleteConfirmId, setDeleteConfirmId] = useState<string | null>(null)
// Fetch levels
const { data: levels, isLoading, error } = useQuery<Level[]>({
queryKey: ['levels'],
queryFn: async () => {
const res = await apiFetch('/api/levels')
if (!res.ok) throw new Error('Failed to fetch levels')
return res.json()
},
})
// Create level mutation
const createMutation = useMutation({
mutationFn: async (data: LevelFormData) => {
const res = await apiFetch('/api/levels', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
})
if (!res.ok) {
const error = await res.json()
throw new Error(error.error || 'Failed to create level')
}
return res.json()
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['levels'] })
},
})
// Update level mutation
const updateMutation = useMutation({
mutationFn: async ({ id, data }: { id: string; data: LevelFormData }) => {
const res = await apiFetch('/api/levels', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ id, ...data }),
})
if (!res.ok) {
const error = await res.json()
throw new Error(error.error || 'Failed to update level')
}
return res.json()
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['levels'] })
},
})
// Delete level mutation
const deleteMutation = useMutation({
mutationFn: async (id: string) => {
const res = await apiFetch(`/api/levels?id=${id}`, {
method: 'DELETE',
})
if (!res.ok) {
const error = await res.json()
throw new Error(error.error || 'Failed to delete level')
}
return res.json()
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['levels'] })
setDeleteConfirmId(null)
},
})
const handleOpenCreate = () => {
setEditingLevel(null)
setIsDialogOpen(true)
}
const handleOpenEdit = (level: Level) => {
setEditingLevel(level)
setIsDialogOpen(true)
}
const handleDelete = (id: string) => {
if (deleteConfirmId === id) {
deleteMutation.mutate(id)
} else {
setDeleteConfirmId(id)
// Reset after 3 seconds
setTimeout(() => setDeleteConfirmId(null), 3000)
}
}
const handleSubmit = async (data: LevelFormData) => {
if (editingLevel) {
await updateMutation.mutateAsync({ id: editingLevel.id, data })
} else {
await createMutation.mutateAsync(data)
}
}
if (isLoading) {
return (
<div className="h-screen flex items-center justify-center">
<Spinner size="lg" />
</div>
)
}
if (error) {
return (
<div className="h-screen flex items-center justify-center">
<div className="text-center">
<p className="text-red-600"></p>
<Button
className="mt-4"
onClick={() => queryClient.invalidateQueries({ queryKey: ['levels'] })}
>
</Button>
</div>
</div>
)
}
return (
<div className="h-screen flex flex-col">
<Header />
<div className="flex-1 overflow-auto p-6">
<div>
<div className="flex items-center justify-between mb-6">
<div>
<h1 className="text-2xl font-bold"></h1>
<p className="text-gray-500 mt-1">
{levels?.length || 0}
</p>
</div>
<Button onClick={handleOpenCreate}>
<Plus className="h-4 w-4 mr-2" />
</Button>
</div>
<LevelTable
levels={levels || []}
onEdit={handleOpenEdit}
onDelete={handleDelete}
deleteConfirmId={deleteConfirmId}
/>
</div>
</div>
<LevelDialog
open={isDialogOpen}
onOpenChange={setIsDialogOpen}
level={editingLevel}
onSubmit={handleSubmit}
/>
</div>
)
}