initial version of the app
This commit is contained in:
@@ -0,0 +1,290 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Calendar, Clock, MapPin, ChevronLeft, ChevronRight } from 'lucide-react';
|
||||
import { useToast } from '@/hooks/use-toast';
|
||||
|
||||
interface Court {
|
||||
id: string;
|
||||
name: string;
|
||||
isActive: boolean;
|
||||
}
|
||||
|
||||
interface Booking {
|
||||
id: string;
|
||||
courtId: string;
|
||||
date: string;
|
||||
startTime: string;
|
||||
endTime: string;
|
||||
status: string;
|
||||
userId: string;
|
||||
}
|
||||
|
||||
interface BookingSlot {
|
||||
time: string;
|
||||
courtId: string;
|
||||
courtName: string;
|
||||
available: boolean;
|
||||
bookingId?: string;
|
||||
}
|
||||
|
||||
export function BookingCalendar() {
|
||||
const [selectedDate, setSelectedDate] = useState(new Date());
|
||||
const [courts, setCourts] = useState<Court[]>([]);
|
||||
const [bookings, setBookings] = useState<Booking[]>([]);
|
||||
const [bookingSlots, setBookingSlots] = useState<BookingSlot[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const { toast } = useToast();
|
||||
|
||||
// Time slots for booking (7 PM to 11 PM)
|
||||
const timeSlots = ['19:00', '20:00', '21:00', '22:00'];
|
||||
|
||||
useEffect(() => {
|
||||
fetchCourts();
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (courts.length > 0) {
|
||||
fetchBookings();
|
||||
}
|
||||
}, [selectedDate, courts]);
|
||||
|
||||
const fetchCourts = async () => {
|
||||
try {
|
||||
const response = await fetch('/api/admin/courts');
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
setCourts(data.courts.filter((court: Court) => court.isActive));
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error fetching courts:', error);
|
||||
toast({
|
||||
title: 'Error',
|
||||
description: 'Failed to fetch courts',
|
||||
variant: 'destructive',
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const fetchBookings = async () => {
|
||||
try {
|
||||
const response = await fetch('/api/bookings');
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
setBookings(data.bookings);
|
||||
generateBookingSlots(data.bookings);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error fetching bookings:', error);
|
||||
toast({
|
||||
title: 'Error',
|
||||
description: 'Failed to fetch bookings',
|
||||
variant: 'destructive',
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const generateBookingSlots = (existingBookings: Booking[]) => {
|
||||
const dateStr = selectedDate.toISOString().split('T')[0];
|
||||
const slots: BookingSlot[] = [];
|
||||
|
||||
courts.forEach((court) => {
|
||||
timeSlots.forEach((time) => {
|
||||
const existingBooking = existingBookings.find(
|
||||
(booking) =>
|
||||
booking.courtId === court.id &&
|
||||
booking.date === dateStr &&
|
||||
booking.startTime === time &&
|
||||
booking.status === 'active'
|
||||
);
|
||||
|
||||
slots.push({
|
||||
time,
|
||||
courtId: court.id,
|
||||
courtName: court.name,
|
||||
available: !existingBooking,
|
||||
bookingId: existingBooking?.id,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
setBookingSlots(slots);
|
||||
};
|
||||
|
||||
const handleBookSlot = async (courtId: string, timeSlot: string) => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const dateStr = selectedDate.toISOString().split('T')[0];
|
||||
|
||||
const response = await fetch('/api/bookings', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
courtId,
|
||||
date: dateStr,
|
||||
timeSlot,
|
||||
}),
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (response.ok) {
|
||||
toast({
|
||||
title: 'Success',
|
||||
description: 'Booking created successfully!',
|
||||
});
|
||||
fetchBookings(); // Refresh bookings
|
||||
} else {
|
||||
toast({
|
||||
title: 'Error',
|
||||
description: data.error || 'Failed to create booking',
|
||||
variant: 'destructive',
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error booking slot:', error);
|
||||
toast({
|
||||
title: 'Error',
|
||||
description: 'Failed to create booking',
|
||||
variant: 'destructive',
|
||||
});
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const navigateDate = (direction: 'prev' | 'next') => {
|
||||
const newDate = new Date(selectedDate);
|
||||
newDate.setDate(newDate.getDate() + (direction === 'next' ? 1 : -1));
|
||||
setSelectedDate(newDate);
|
||||
};
|
||||
|
||||
const isToday = (date: Date) => {
|
||||
const today = new Date();
|
||||
return date.toDateString() === today.toDateString();
|
||||
};
|
||||
|
||||
const isPastDate = (date: Date) => {
|
||||
const today = new Date();
|
||||
today.setHours(0, 0, 0, 0);
|
||||
return date < today;
|
||||
};
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className='flex items-center gap-2'>
|
||||
<Calendar className='h-5 w-5' />
|
||||
Book Your Court
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className='space-y-6'>
|
||||
{/* Date Navigation */}
|
||||
<div className='flex items-center justify-between'>
|
||||
<Button
|
||||
variant='outline'
|
||||
size='sm'
|
||||
onClick={() => navigateDate('prev')}
|
||||
disabled={isPastDate(new Date(selectedDate.getTime() - 24 * 60 * 60 * 1000))}
|
||||
>
|
||||
<ChevronLeft className='h-4 w-4' />
|
||||
Previous Day
|
||||
</Button>
|
||||
|
||||
<h3 className='text-lg font-semibold'>
|
||||
{selectedDate.toLocaleDateString('en-US', {
|
||||
weekday: 'long',
|
||||
year: 'numeric',
|
||||
month: 'long',
|
||||
day: 'numeric',
|
||||
})}
|
||||
{isToday(selectedDate) && <span className='text-sm text-blue-600 ml-2'>(Today)</span>}
|
||||
</h3>
|
||||
|
||||
<Button variant='outline' size='sm' onClick={() => navigateDate('next')}>
|
||||
Next Day
|
||||
<ChevronRight className='h-4 w-4' />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Loading State */}
|
||||
{loading && (
|
||||
<div className='text-center py-8'>
|
||||
<div className='inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900'></div>
|
||||
<p className='mt-2 text-sm text-gray-500'>Loading booking slots...</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* No Courts Available */}
|
||||
{!loading && courts.length === 0 && (
|
||||
<div className='text-center py-8'>
|
||||
<p className='text-gray-500'>No courts available for booking</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Past Date Warning */}
|
||||
{isPastDate(selectedDate) && (
|
||||
<div className='bg-yellow-50 border border-yellow-200 rounded-lg p-4'>
|
||||
<p className='text-yellow-800 text-sm'>
|
||||
You cannot book courts for past dates. Please select a current or future date.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Time Slots Grid */}
|
||||
{!loading && courts.length > 0 && !isPastDate(selectedDate) && (
|
||||
<div className='grid grid-cols-1 md:grid-cols-2 gap-4'>
|
||||
{bookingSlots.map((slot, index) => (
|
||||
<div
|
||||
key={`${slot.courtId}-${slot.time}`}
|
||||
className={`p-4 border rounded-lg transition-colors ${
|
||||
slot.available
|
||||
? 'border-green-200 bg-green-50 hover:bg-green-100'
|
||||
: 'border-red-200 bg-red-50'
|
||||
}`}
|
||||
>
|
||||
<div className='flex items-center justify-between'>
|
||||
<div className='space-y-2'>
|
||||
<div className='flex items-center gap-2 text-sm font-medium'>
|
||||
<Clock className='h-4 w-4' />
|
||||
{slot.time} -{' '}
|
||||
{String(parseInt(slot.time.split(':')[0]) + 1).padStart(2, '0')}:00
|
||||
</div>
|
||||
<div className='flex items-center gap-2 text-sm text-gray-600'>
|
||||
<MapPin className='h-4 w-4' />
|
||||
{slot.courtName}
|
||||
</div>
|
||||
{!slot.available && (
|
||||
<div className='text-xs text-red-600'>Already booked</div>
|
||||
)}
|
||||
</div>
|
||||
<Button
|
||||
size='sm'
|
||||
disabled={!slot.available || loading}
|
||||
onClick={() => handleBookSlot(slot.courtId, slot.time)}
|
||||
className={slot.available ? 'bg-green-600 hover:bg-green-700' : ''}
|
||||
>
|
||||
{slot.available ? 'Book' : 'Booked'}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* No Slots Message */}
|
||||
{!loading && courts.length > 0 && bookingSlots.length === 0 && !isPastDate(selectedDate) && (
|
||||
<div className='text-center py-8'>
|
||||
<p className='text-gray-500'>No booking slots available for this date</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,525 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
|
||||
import { Calendar, Clock, MapPin, ChevronLeft, ChevronRight, Users, User } from 'lucide-react';
|
||||
import { useToast } from '@/hooks/use-toast';
|
||||
|
||||
interface Court {
|
||||
id: string;
|
||||
name: string;
|
||||
isActive: boolean;
|
||||
}
|
||||
|
||||
interface Booking {
|
||||
id: string;
|
||||
courtId: string;
|
||||
date: string;
|
||||
startTime: string;
|
||||
endTime: string;
|
||||
status: string;
|
||||
userId: string;
|
||||
notes?: string;
|
||||
}
|
||||
|
||||
interface BookingSlot {
|
||||
time: string;
|
||||
courtId: string;
|
||||
courtName: string;
|
||||
available: boolean;
|
||||
bookingId?: string;
|
||||
}
|
||||
|
||||
interface Settings {
|
||||
booking_window_days: string;
|
||||
booking_start_time: string;
|
||||
booking_end_time: string;
|
||||
allow_weekend_bookings: string;
|
||||
}
|
||||
|
||||
export function EnhancedBookingCalendar() {
|
||||
const [selectedDate, setSelectedDate] = useState(new Date());
|
||||
const [courts, setCourts] = useState<Court[]>([]);
|
||||
const [bookings, setBookings] = useState<Booking[]>([]);
|
||||
const [bookingSlots, setBookingSlots] = useState<BookingSlot[]>([]);
|
||||
const [settings, setSettings] = useState<Settings | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [partnerName, setPartnerName] = useState('');
|
||||
const [notes, setNotes] = useState('');
|
||||
const [showBookingDialog, setShowBookingDialog] = useState(false);
|
||||
const [selectedSlot, setSelectedSlot] = useState<BookingSlot | null>(null);
|
||||
const { toast } = useToast();
|
||||
|
||||
useEffect(() => {
|
||||
fetchSettings();
|
||||
fetchCourts();
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (courts.length > 0 && settings) {
|
||||
fetchBookings();
|
||||
}
|
||||
}, [selectedDate, courts, settings]);
|
||||
|
||||
// Fetch settings from public endpoint (not admin)
|
||||
const fetchSettings = async () => {
|
||||
try {
|
||||
const response = await fetch('/api/settings');
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
const settingsMap: Settings = {
|
||||
booking_window_days: '7',
|
||||
booking_start_time: '08:00',
|
||||
booking_end_time: '22:00',
|
||||
allow_weekend_bookings: 'true',
|
||||
};
|
||||
|
||||
data.settings.forEach((setting: any) => {
|
||||
if (setting.key in settingsMap) {
|
||||
settingsMap[setting.key as keyof Settings] = setting.value;
|
||||
}
|
||||
});
|
||||
|
||||
setSettings(settingsMap);
|
||||
} else {
|
||||
// If settings fetch fails, use defaults
|
||||
setSettings({
|
||||
booking_window_days: '7',
|
||||
booking_start_time: '08:00',
|
||||
booking_end_time: '22:00',
|
||||
allow_weekend_bookings: 'true',
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error fetching settings:', error);
|
||||
// Set default settings
|
||||
setSettings({
|
||||
booking_window_days: '7',
|
||||
booking_start_time: '08:00',
|
||||
booking_end_time: '22:00',
|
||||
allow_weekend_bookings: 'true',
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// Fetch courts from public endpoint (not admin)
|
||||
const fetchCourts = async () => {
|
||||
try {
|
||||
const response = await fetch('/api/courts');
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
setCourts(data.courts.filter((court: Court) => court.isActive));
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error fetching courts:', error);
|
||||
toast({
|
||||
title: 'Error',
|
||||
description: 'Failed to fetch courts',
|
||||
variant: 'destructive',
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const fetchBookings = async () => {
|
||||
try {
|
||||
const response = await fetch('/api/bookings');
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
setBookings(data.bookings);
|
||||
generateBookingSlots(data.bookings);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error fetching bookings:', error);
|
||||
toast({
|
||||
title: 'Error',
|
||||
description: 'Failed to fetch bookings',
|
||||
variant: 'destructive',
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const generateTimeSlots = (): string[] => {
|
||||
if (!settings) return [];
|
||||
|
||||
const start = parseInt(settings.booking_start_time.split(':')[0]);
|
||||
const end = parseInt(settings.booking_end_time.split(':')[0]);
|
||||
const slots = [];
|
||||
|
||||
for (let hour = start; hour < end; hour++) {
|
||||
slots.push(`${hour.toString().padStart(2, '0')}:00`);
|
||||
}
|
||||
|
||||
return slots;
|
||||
};
|
||||
|
||||
const generateBookingSlots = (existingBookings: Booking[]) => {
|
||||
const dateStr = selectedDate.toISOString().split('T')[0];
|
||||
const timeSlots = generateTimeSlots();
|
||||
const slots: BookingSlot[] = [];
|
||||
|
||||
courts.forEach((court) => {
|
||||
timeSlots.forEach((time) => {
|
||||
const existingBooking = existingBookings.find(
|
||||
(booking) =>
|
||||
booking.courtId === court.id &&
|
||||
booking.date === dateStr &&
|
||||
booking.startTime === time &&
|
||||
booking.status === 'active'
|
||||
);
|
||||
|
||||
slots.push({
|
||||
time,
|
||||
courtId: court.id,
|
||||
courtName: court.name,
|
||||
available: !existingBooking,
|
||||
bookingId: existingBooking?.id,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
setBookingSlots(slots);
|
||||
};
|
||||
|
||||
const isDateSelectable = (date: Date): boolean => {
|
||||
if (!settings) return false;
|
||||
|
||||
const today = new Date();
|
||||
today.setHours(0, 0, 0, 0);
|
||||
|
||||
const selectedDateOnly = new Date(date);
|
||||
selectedDateOnly.setHours(0, 0, 0, 0);
|
||||
|
||||
// Check if date is in the past
|
||||
if (selectedDateOnly < today) return false;
|
||||
|
||||
// Check booking window
|
||||
const maxDate = new Date(today);
|
||||
maxDate.setDate(today.getDate() + parseInt(settings.booking_window_days));
|
||||
if (selectedDateOnly > maxDate) return false;
|
||||
|
||||
// Check weekend restrictions
|
||||
if (settings.allow_weekend_bookings === 'false') {
|
||||
const dayOfWeek = selectedDateOnly.getDay();
|
||||
if (dayOfWeek === 0 || dayOfWeek === 6) return false; // Sunday or Saturday
|
||||
}
|
||||
|
||||
return true;
|
||||
};
|
||||
|
||||
const handleSlotClick = (slot: BookingSlot) => {
|
||||
if (!slot.available) return;
|
||||
|
||||
setSelectedSlot(slot);
|
||||
setPartnerName('');
|
||||
setNotes('');
|
||||
setShowBookingDialog(true);
|
||||
};
|
||||
|
||||
const handleBookingConfirm = async () => {
|
||||
if (!selectedSlot) return;
|
||||
|
||||
setLoading(true);
|
||||
try {
|
||||
const dateStr = selectedDate.toISOString().split('T')[0];
|
||||
const bookingNotes = [];
|
||||
|
||||
if (partnerName.trim()) {
|
||||
bookingNotes.push(`Partner: ${partnerName.trim()}`);
|
||||
}
|
||||
if (notes.trim()) {
|
||||
bookingNotes.push(notes.trim());
|
||||
}
|
||||
|
||||
const response = await fetch('/api/bookings', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
courtId: selectedSlot.courtId,
|
||||
date: dateStr,
|
||||
timeSlot: selectedSlot.time,
|
||||
notes: bookingNotes.join(' | '),
|
||||
}),
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (response.ok) {
|
||||
toast({
|
||||
title: 'Success',
|
||||
description: 'Booking created successfully!',
|
||||
});
|
||||
setShowBookingDialog(false);
|
||||
fetchBookings(); // Refresh bookings
|
||||
} else {
|
||||
toast({
|
||||
title: 'Error',
|
||||
description: data.error || 'Failed to create booking',
|
||||
variant: 'destructive',
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error booking slot:', error);
|
||||
toast({
|
||||
title: 'Error',
|
||||
description: 'Failed to create booking',
|
||||
variant: 'destructive',
|
||||
});
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const navigateDate = (direction: 'prev' | 'next') => {
|
||||
const newDate = new Date(selectedDate);
|
||||
newDate.setDate(newDate.getDate() + (direction === 'next' ? 1 : -1));
|
||||
|
||||
if (isDateSelectable(newDate)) {
|
||||
setSelectedDate(newDate);
|
||||
}
|
||||
};
|
||||
|
||||
const getAvailableDates = (): Date[] => {
|
||||
if (!settings) return [];
|
||||
|
||||
const dates: Date[] = [];
|
||||
const today = new Date();
|
||||
const maxDays = parseInt(settings.booking_window_days);
|
||||
|
||||
for (let i = 0; i <= maxDays; i++) {
|
||||
const date = new Date(today);
|
||||
date.setDate(today.getDate() + i);
|
||||
|
||||
if (isDateSelectable(date)) {
|
||||
dates.push(date);
|
||||
}
|
||||
}
|
||||
|
||||
return dates;
|
||||
};
|
||||
|
||||
const isPastDate = (date: Date) => {
|
||||
const today = new Date();
|
||||
today.setHours(0, 0, 0, 0);
|
||||
return date < today;
|
||||
};
|
||||
|
||||
const isToday = (date: Date) => {
|
||||
const today = new Date();
|
||||
return date.toDateString() === today.toDateString();
|
||||
};
|
||||
|
||||
if (!settings) {
|
||||
return (
|
||||
<Card>
|
||||
<CardContent className='p-6'>
|
||||
<div className='flex items-center justify-center'>
|
||||
<div className='animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900'></div>
|
||||
<p className='ml-2'>Loading booking system...</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className='space-y-6'>
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className='flex items-center gap-2'>
|
||||
<Calendar className='h-5 w-5' />
|
||||
Book Your Court
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{/* Mobile-friendly date navigation */}
|
||||
<div className='space-y-6'>
|
||||
{/* Quick Date Selection */}
|
||||
<div className='space-y-4'>
|
||||
<h3 className='font-medium'>Select Date</h3>
|
||||
<div className='grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-2'>
|
||||
{getAvailableDates()
|
||||
.slice(0, 8)
|
||||
.map((date, index) => (
|
||||
<Button
|
||||
key={index}
|
||||
variant={
|
||||
date.toDateString() === selectedDate.toDateString()
|
||||
? 'default'
|
||||
: 'outline'
|
||||
}
|
||||
size='sm'
|
||||
onClick={() => setSelectedDate(date)}
|
||||
className='h-16 flex flex-col'
|
||||
>
|
||||
<span className='text-xs font-normal'>
|
||||
{date.toLocaleDateString('en-US', { weekday: 'short' })}
|
||||
</span>
|
||||
<span className='font-semibold'>{date.getDate()}</span>
|
||||
<span className='text-xs font-normal'>
|
||||
{date.toLocaleDateString('en-US', { month: 'short' })}
|
||||
</span>
|
||||
{isToday(date) && <span className='text-xs text-blue-600'>Today</span>}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Selected Date Display */}
|
||||
<div className='text-center p-4 bg-blue-50 rounded-lg'>
|
||||
<h3 className='text-lg font-semibold text-blue-900'>
|
||||
{selectedDate.toLocaleDateString('en-US', {
|
||||
weekday: 'long',
|
||||
year: 'numeric',
|
||||
month: 'long',
|
||||
day: 'numeric',
|
||||
})}
|
||||
</h3>
|
||||
{isToday(selectedDate) && <span className='text-sm text-blue-600'>Today</span>}
|
||||
</div>
|
||||
|
||||
{/* Loading State */}
|
||||
{loading && (
|
||||
<div className='text-center py-8'>
|
||||
<div className='inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900'></div>
|
||||
<p className='mt-2 text-sm text-gray-500'>Loading booking slots...</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* No Courts Available */}
|
||||
{!loading && courts.length === 0 && (
|
||||
<div className='text-center py-8'>
|
||||
<p className='text-gray-500'>No courts available for booking</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Time Slots Grid */}
|
||||
{!loading && courts.length > 0 && (
|
||||
<div className='space-y-4'>
|
||||
<h3 className='font-medium'>Available Time Slots</h3>
|
||||
<div className='grid grid-cols-1 sm:grid-cols-2 gap-4'>
|
||||
{bookingSlots.map((slot, index) => (
|
||||
<div
|
||||
key={`${slot.courtId}-${slot.time}`}
|
||||
className={`p-4 border rounded-lg transition-colors cursor-pointer ${
|
||||
slot.available
|
||||
? 'border-green-200 bg-green-50 hover:bg-green-100'
|
||||
: 'border-red-200 bg-red-50 cursor-not-allowed'
|
||||
}`}
|
||||
onClick={() => handleSlotClick(slot)}
|
||||
>
|
||||
<div className='flex items-center justify-between'>
|
||||
<div className='space-y-2'>
|
||||
<div className='flex items-center gap-2 text-sm font-medium'>
|
||||
<Clock className='h-4 w-4' />
|
||||
{slot.time} -{' '}
|
||||
{String(parseInt(slot.time.split(':')[0]) + 1).padStart(2, '0')}
|
||||
:00
|
||||
</div>
|
||||
<div className='flex items-center gap-2 text-sm text-gray-600'>
|
||||
<MapPin className='h-4 w-4' />
|
||||
{slot.courtName}
|
||||
</div>
|
||||
{!slot.available && (
|
||||
<div className='text-xs text-red-600'>Already booked</div>
|
||||
)}
|
||||
</div>
|
||||
<Button
|
||||
size='sm'
|
||||
disabled={!slot.available}
|
||||
className={slot.available ? 'bg-green-600 hover:bg-green-700' : ''}
|
||||
>
|
||||
{slot.available ? 'Book' : 'Booked'}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* No Slots Message */}
|
||||
{!loading && courts.length > 0 && bookingSlots.length === 0 && (
|
||||
<div className='text-center py-8'>
|
||||
<p className='text-gray-500'>No booking slots available for this date</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Booking Dialog */}
|
||||
<Dialog open={showBookingDialog} onOpenChange={setShowBookingDialog}>
|
||||
<DialogContent className='sm:max-w-md'>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Confirm Your Booking</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className='space-y-4'>
|
||||
{selectedSlot && (
|
||||
<div className='bg-blue-50 p-4 rounded-lg space-y-2'>
|
||||
<div className='flex items-center gap-2 text-sm'>
|
||||
<Calendar className='h-4 w-4' />
|
||||
{selectedDate.toLocaleDateString('en-US', {
|
||||
weekday: 'long',
|
||||
month: 'long',
|
||||
day: 'numeric',
|
||||
})}
|
||||
</div>
|
||||
<div className='flex items-center gap-2 text-sm'>
|
||||
<Clock className='h-4 w-4' />
|
||||
{selectedSlot.time} -{' '}
|
||||
{String(parseInt(selectedSlot.time.split(':')[0]) + 1).padStart(2, '0')}:00
|
||||
</div>
|
||||
<div className='flex items-center gap-2 text-sm'>
|
||||
<MapPin className='h-4 w-4' />
|
||||
{selectedSlot.courtName}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className='space-y-2'>
|
||||
<Label htmlFor='partner'>Playing Partner (Optional)</Label>
|
||||
<div className='relative'>
|
||||
<User className='absolute left-3 top-3 h-4 w-4 text-gray-400' />
|
||||
<Input
|
||||
id='partner'
|
||||
placeholder='Who will you be playing with?'
|
||||
value={partnerName}
|
||||
onChange={(e) => setPartnerName(e.target.value)}
|
||||
className='pl-10'
|
||||
/>
|
||||
</div>
|
||||
<p className='text-xs text-gray-500'>Enter the name of the person you'll be playing with</p>
|
||||
</div>
|
||||
|
||||
<div className='space-y-2'>
|
||||
<Label htmlFor='notes'>Additional Notes (Optional)</Label>
|
||||
<Textarea
|
||||
id='notes'
|
||||
placeholder='Any additional information...'
|
||||
value={notes}
|
||||
onChange={(e) => setNotes(e.target.value)}
|
||||
className='min-h-[80px]'
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className='flex gap-2 pt-4'>
|
||||
<Button variant='outline' className='flex-1' onClick={() => setShowBookingDialog(false)}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button className='flex-1' onClick={handleBookingConfirm} disabled={loading}>
|
||||
{loading ? 'Booking...' : 'Confirm Booking'}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,429 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from '@/components/ui/alert-dialog';
|
||||
import { Calendar, Clock, MapPin, Edit, Trash2, User, RefreshCw } from 'lucide-react';
|
||||
import { format } from 'date-fns';
|
||||
import { useToast } from '@/hooks/use-toast';
|
||||
|
||||
interface Booking {
|
||||
id: string;
|
||||
date: string;
|
||||
startTime: string;
|
||||
endTime: string;
|
||||
status: string;
|
||||
notes?: string;
|
||||
createdAt: Date;
|
||||
court: {
|
||||
id: string;
|
||||
name: string;
|
||||
};
|
||||
}
|
||||
|
||||
export function UserBookingManagement() {
|
||||
const [bookings, setBookings] = useState<Booking[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [editDialogOpen, setEditDialogOpen] = useState(false);
|
||||
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
|
||||
const [selectedBooking, setSelectedBooking] = useState<Booking | null>(null);
|
||||
const [editNotes, setEditNotes] = useState('');
|
||||
const [editPartner, setEditPartner] = useState('');
|
||||
const { toast } = useToast();
|
||||
|
||||
useEffect(() => {
|
||||
fetchBookings();
|
||||
}, []);
|
||||
|
||||
const fetchBookings = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
const response = await fetch('/api/bookings');
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
// Filter to show only future and today's bookings
|
||||
const now = new Date();
|
||||
const today = now.toISOString().split('T')[0];
|
||||
|
||||
const relevantBookings = data.bookings.filter((booking: Booking) => {
|
||||
if (booking.status !== 'active') return false;
|
||||
return booking.date >= today;
|
||||
});
|
||||
|
||||
setBookings(relevantBookings);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error fetching bookings:', error);
|
||||
toast({
|
||||
title: 'Error',
|
||||
description: 'Failed to fetch your bookings',
|
||||
variant: 'destructive',
|
||||
});
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const parseBookingNotes = (notes?: string) => {
|
||||
if (!notes) return { partner: '', additionalNotes: '' };
|
||||
|
||||
const parts = notes.split(' | ');
|
||||
let partner = '';
|
||||
let additionalNotes = '';
|
||||
|
||||
parts.forEach((part) => {
|
||||
if (part.startsWith('Partner: ')) {
|
||||
partner = part.replace('Partner: ', '');
|
||||
} else {
|
||||
additionalNotes = additionalNotes ? `${additionalNotes} | ${part}` : part;
|
||||
}
|
||||
});
|
||||
|
||||
return { partner, additionalNotes };
|
||||
};
|
||||
|
||||
const handleEditClick = (booking: Booking) => {
|
||||
setSelectedBooking(booking);
|
||||
const { partner, additionalNotes } = parseBookingNotes(booking.notes);
|
||||
setEditPartner(partner);
|
||||
setEditNotes(additionalNotes);
|
||||
setEditDialogOpen(true);
|
||||
};
|
||||
|
||||
const handleDeleteClick = (booking: Booking) => {
|
||||
setSelectedBooking(booking);
|
||||
setDeleteDialogOpen(true);
|
||||
};
|
||||
|
||||
const handleEditSave = async () => {
|
||||
if (!selectedBooking) return;
|
||||
|
||||
try {
|
||||
const bookingNotes = [];
|
||||
if (editPartner.trim()) {
|
||||
bookingNotes.push(`Partner: ${editPartner.trim()}`);
|
||||
}
|
||||
if (editNotes.trim()) {
|
||||
bookingNotes.push(editNotes.trim());
|
||||
}
|
||||
|
||||
const response = await fetch(`/api/bookings/${selectedBooking.id}`, {
|
||||
method: 'PATCH',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
notes: bookingNotes.join(' | '),
|
||||
}),
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
toast({
|
||||
title: 'Success',
|
||||
description: 'Booking updated successfully',
|
||||
});
|
||||
setEditDialogOpen(false);
|
||||
fetchBookings();
|
||||
} else {
|
||||
const data = await response.json();
|
||||
toast({
|
||||
title: 'Error',
|
||||
description: data.error || 'Failed to update booking',
|
||||
variant: 'destructive',
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error updating booking:', error);
|
||||
toast({
|
||||
title: 'Error',
|
||||
description: 'Failed to update booking',
|
||||
variant: 'destructive',
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const handleDeleteConfirm = async () => {
|
||||
if (!selectedBooking) return;
|
||||
|
||||
try {
|
||||
const response = await fetch(`/api/bookings/${selectedBooking.id}`, {
|
||||
method: 'DELETE',
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
toast({
|
||||
title: 'Success',
|
||||
description: 'Booking cancelled successfully',
|
||||
});
|
||||
setDeleteDialogOpen(false);
|
||||
fetchBookings();
|
||||
} else {
|
||||
const data = await response.json();
|
||||
toast({
|
||||
title: 'Error',
|
||||
description: data.error || 'Failed to cancel booking',
|
||||
variant: 'destructive',
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error cancelling booking:', error);
|
||||
toast({
|
||||
title: 'Error',
|
||||
description: 'Failed to cancel booking',
|
||||
variant: 'destructive',
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const formatDate = (dateStr: string) => {
|
||||
try {
|
||||
const date = new Date(dateStr);
|
||||
return format(date, 'EEE, MMM dd');
|
||||
} catch {
|
||||
return dateStr;
|
||||
}
|
||||
};
|
||||
|
||||
const isToday = (dateStr: string) => {
|
||||
const today = new Date().toISOString().split('T')[0];
|
||||
return dateStr === today;
|
||||
};
|
||||
|
||||
const canModifyBooking = (booking: Booking) => {
|
||||
const bookingDateTime = new Date(`${booking.date}T${booking.startTime}`);
|
||||
const now = new Date();
|
||||
const timeDiff = bookingDateTime.getTime() - now.getTime();
|
||||
const hoursDiff = timeDiff / (1000 * 60 * 60);
|
||||
|
||||
// Allow modifications if booking is more than 2 hours away
|
||||
return hoursDiff > 2;
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader className='pb-3'>
|
||||
<CardTitle className='text-base flex items-center gap-2'>
|
||||
<Calendar className='h-4 w-4' />
|
||||
Your Bookings
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className='space-y-3'>
|
||||
{[1, 2, 3].map((i) => (
|
||||
<div key={i} className='animate-pulse border rounded-lg p-4'>
|
||||
<div className='h-4 bg-gray-200 rounded w-3/4 mb-2'></div>
|
||||
<div className='h-3 bg-gray-200 rounded w-1/2'></div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Card>
|
||||
<CardHeader className='pb-3 flex flex-row items-center justify-between'>
|
||||
<CardTitle className='text-base flex items-center gap-2'>
|
||||
<Calendar className='h-4 w-4' />
|
||||
Your Bookings
|
||||
</CardTitle>
|
||||
<Button size='sm' variant='outline' onClick={fetchBookings}>
|
||||
<RefreshCw className='h-4 w-4' />
|
||||
</Button>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{bookings.length === 0 ? (
|
||||
<div className='text-sm text-gray-500 text-center py-6'>
|
||||
No upcoming bookings. Make your first booking!
|
||||
</div>
|
||||
) : (
|
||||
<div className='space-y-3'>
|
||||
{bookings.map((booking) => {
|
||||
const { partner, additionalNotes } = parseBookingNotes(booking.notes);
|
||||
const canModify = canModifyBooking(booking);
|
||||
|
||||
return (
|
||||
<div key={booking.id} className='border rounded-lg p-4 space-y-3'>
|
||||
<div className='flex items-start justify-between'>
|
||||
<div className='space-y-2 flex-1'>
|
||||
<div className='flex items-center gap-2'>
|
||||
<MapPin className='h-4 w-4 text-blue-600' />
|
||||
<span className='font-medium text-sm'>{booking.court.name}</span>
|
||||
{isToday(booking.date) && (
|
||||
<Badge variant='secondary' className='text-xs'>
|
||||
Today
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className='flex items-center gap-4 text-xs text-gray-500'>
|
||||
<div className='flex items-center gap-1'>
|
||||
<Calendar className='h-3 w-3' />
|
||||
<span>{formatDate(booking.date)}</span>
|
||||
</div>
|
||||
<div className='flex items-center gap-1'>
|
||||
<Clock className='h-3 w-3' />
|
||||
<span>
|
||||
{booking.startTime} - {booking.endTime}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{partner && (
|
||||
<div className='flex items-center gap-1 text-xs text-gray-600'>
|
||||
<User className='h-3 w-3' />
|
||||
<span>Playing with: {partner}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{additionalNotes && (
|
||||
<p className='text-xs text-gray-600 italic bg-gray-50 p-2 rounded'>
|
||||
{additionalNotes}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className='flex gap-1 ml-2'>
|
||||
<Button
|
||||
size='sm'
|
||||
variant='outline'
|
||||
onClick={() => handleEditClick(booking)}
|
||||
disabled={!canModify}
|
||||
className='h-8 w-8 p-0'
|
||||
>
|
||||
<Edit className='h-3 w-3' />
|
||||
</Button>
|
||||
<Button
|
||||
size='sm'
|
||||
variant='outline'
|
||||
onClick={() => handleDeleteClick(booking)}
|
||||
disabled={!canModify}
|
||||
className='h-8 w-8 p-0 text-red-600 hover:text-red-700'
|
||||
>
|
||||
<Trash2 className='h-3 w-3' />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{!canModify && (
|
||||
<p className='text-xs text-amber-600 bg-amber-50 p-2 rounded'>
|
||||
Booking can only be modified more than 2 hours before the session
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Edit Dialog */}
|
||||
<Dialog open={editDialogOpen} onOpenChange={setEditDialogOpen}>
|
||||
<DialogContent className='sm:max-w-md'>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Edit Booking</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className='space-y-4'>
|
||||
{selectedBooking && (
|
||||
<div className='bg-blue-50 p-4 rounded-lg space-y-2'>
|
||||
<div className='flex items-center gap-2 text-sm'>
|
||||
<Calendar className='h-4 w-4' />
|
||||
{formatDate(selectedBooking.date)}
|
||||
</div>
|
||||
<div className='flex items-center gap-2 text-sm'>
|
||||
<Clock className='h-4 w-4' />
|
||||
{selectedBooking.startTime} - {selectedBooking.endTime}
|
||||
</div>
|
||||
<div className='flex items-center gap-2 text-sm'>
|
||||
<MapPin className='h-4 w-4' />
|
||||
{selectedBooking.court.name}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className='space-y-2'>
|
||||
<Label htmlFor='edit-partner'>Playing Partner</Label>
|
||||
<div className='relative'>
|
||||
<User className='absolute left-3 top-3 h-4 w-4 text-gray-400' />
|
||||
<Input
|
||||
id='edit-partner'
|
||||
placeholder='Who will you be playing with?'
|
||||
value={editPartner}
|
||||
onChange={(e) => setEditPartner(e.target.value)}
|
||||
className='pl-10'
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className='space-y-2'>
|
||||
<Label htmlFor='edit-notes'>Additional Notes</Label>
|
||||
<Textarea
|
||||
id='edit-notes'
|
||||
placeholder='Any additional information...'
|
||||
value={editNotes}
|
||||
onChange={(e) => setEditNotes(e.target.value)}
|
||||
className='min-h-[80px]'
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className='flex gap-2 pt-4'>
|
||||
<Button variant='outline' className='flex-1' onClick={() => setEditDialogOpen(false)}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button className='flex-1' onClick={handleEditSave}>
|
||||
Save Changes
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{/* Delete Confirmation Dialog */}
|
||||
<AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Cancel Booking</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
Are you sure you want to cancel this booking? This action cannot be undone.
|
||||
{selectedBooking && (
|
||||
<div className='mt-3 p-3 bg-gray-50 rounded'>
|
||||
<p className='text-sm font-medium'>
|
||||
{selectedBooking.court.name} - {formatDate(selectedBooking.date)}
|
||||
</p>
|
||||
<p className='text-sm text-gray-600'>
|
||||
{selectedBooking.startTime} - {selectedBooking.endTime}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Keep Booking</AlertDialogCancel>
|
||||
<AlertDialogAction onClick={handleDeleteConfirm} className='bg-red-600 hover:bg-red-700'>
|
||||
Cancel Booking
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user