'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>
	);
}
