'use client';

import { useState } from 'react';
import { Calendar } from '@/components/ui/calendar';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { CalendarIcon, Clock, MapPin } from 'lucide-react';
import { useToast } from '@/hooks/use-toast';

const timeSlots = [
	'09:00',
	'10:00',
	'11:00',
	'12:00',
	'13:00',
	'14:00',
	'15:00',
	'16:00',
	'17:00',
	'18:00',
	'19:00',
	'20:00',
];

const courts = [
	{ id: 'court-1', name: 'Court 1', isActive: true },
	{ id: 'court-2', name: 'Court 2', isActive: true },
];

export function BookingCalendar() {
	const [selectedDate, setSelectedDate] = useState<Date>(new Date());
	const [selectedSlot, setSelectedSlot] = useState<string | null>(null);
	const [selectedCourt, setSelectedCourt] = useState<string | null>(null);
	const { toast } = useToast();

	const formatDate = (date: Date) => {
		return date.toLocaleDateString('en-IE', {
			weekday: 'long',
			year: 'numeric',
			month: 'long',
			day: 'numeric',
		});
	};

	const handleBooking = async () => {
		if (!selectedDate || !selectedSlot || !selectedCourt) {
			return;
		}

		try {
			const response = await fetch('/api/bookings', {
				method: 'POST',
				headers: {
					'Content-Type': 'application/json',
				},
				body: JSON.stringify({
					courtId: selectedCourt,
					date: selectedDate.toISOString().split('T')[0],
					timeSlot: selectedSlot,
				}),
			});

			const result = await response.json();

			if (response.ok) {
				// Reset selections and show success
				setSelectedSlot(null);
				setSelectedCourt(null);
				// Show success message
				toast({
					title: 'Success',
					description: 'Booking created successfully!',
				});
			} else {
				toast({
					title: 'Error',
					description: result.error || 'Booking failed',
					variant: 'destructive',
				});
			}
		} catch (error) {
			console.error('Booking error:', error);
			toast({
				title: 'Error',
				description: 'An error occurred while creating the booking',
				variant: 'destructive',
			});
		}
	};

	return (
		<div className='grid gap-6 lg:grid-cols-2'>
			{/* Calendar */}
			<Card>
				<CardHeader>
					<CardTitle className='flex items-center gap-2'>
						<CalendarIcon className='h-5 w-5' />
						Select Date
					</CardTitle>
					<CardDescription>Choose the date for your table tennis session</CardDescription>
				</CardHeader>
				<CardContent>
					<Calendar
						mode='single'
						selected={selectedDate}
						onSelect={(date) => date && setSelectedDate(date)}
						disabled={(date) => date < new Date() || date.getDay() === 0} // Disable past dates and Sundays
						className='rounded-md border'
					/>
				</CardContent>
			</Card>

			{/* Time Slots and Courts */}
			<Card>
				<CardHeader>
					<CardTitle className='flex items-center gap-2'>
						<Clock className='h-5 w-5' />
						Available Slots
					</CardTitle>
					<CardDescription>{selectedDate ? formatDate(selectedDate) : 'Select a date first'}</CardDescription>
				</CardHeader>
				<CardContent className='space-y-6'>
					{/* Court Selection */}
					<div>
						<h4 className='font-medium mb-3 flex items-center gap-2'>
							<MapPin className='h-4 w-4' />
							Select Court
						</h4>
						<div className='grid grid-cols-2 gap-2'>
							{courts.map((court) => (
								<Button
									key={court.id}
									variant={selectedCourt === court.id ? 'default' : 'outline'}
									size='sm'
									onClick={() => setSelectedCourt(court.id)}
									disabled={!court.isActive}
								>
									{court.name}
								</Button>
							))}
						</div>
					</div>

					{/* Time Slot Selection */}
					<div>
						<h4 className='font-medium mb-3 flex items-center gap-2'>
							<Clock className='h-4 w-4' />
							Select Time
						</h4>
						<div className='grid grid-cols-3 gap-2'>
							{timeSlots.map((time) => {
								const isBooked = Math.random() > 0.7; // Simulate some bookings
								return (
									<Button
										key={time}
										variant={selectedSlot === time ? 'default' : 'outline'}
										size='sm'
										onClick={() => !isBooked && setSelectedSlot(time)}
										disabled={isBooked}
										className={`relative transition-all ${
											isBooked
												? 'opacity-60 cursor-not-allowed bg-muted/50 border-muted text-muted-foreground hover:opacity-75'
												: ''
										}`}
									>
										{time}
										{isBooked && (
											<Badge
												variant='secondary'
												className='absolute -top-1 -right-1 h-2 w-2 p-0 bg-muted border-muted'
											/>
										)}
									</Button>
								);
							})}
						</div>
					</div>

					{/* Booking Summary */}
					{selectedDate && selectedSlot && selectedCourt && (
						<div className='bg-primary/5 border border-primary/20 rounded-lg p-4 space-y-2 dark:bg-primary/10 dark:border-primary/30'>
							<h4 className='font-medium text-primary dark:text-primary-foreground'>Booking Summary</h4>
							<div className='text-sm text-primary/80 dark:text-primary-foreground/80 space-y-1'>
								<div className='flex items-center gap-2'>
									<CalendarIcon className='h-3 w-3' />
									{formatDate(selectedDate)}
								</div>
								<div className='flex items-center gap-2'>
									<Clock className='h-3 w-3' />
									{selectedSlot} - {String(parseInt(selectedSlot.split(':')[0]) + 1).padStart(2, '0')}
									:00
								</div>
								<div className='flex items-center gap-2'>
									<MapPin className='h-3 w-3' />
									{courts.find((c) => c.id === selectedCourt)?.name}
								</div>
							</div>
							<Button onClick={handleBooking} className='w-full mt-3'>
								Confirm Booking
							</Button>
						</div>
					)}
				</CardContent>
			</Card>
		</div>
	);
}
