import { redirect } from 'next/navigation';
import { getSession } from '@/lib/session';
import { db } from '@/lib/db';
import { users } from '@/lib/db/schema';
import { eq } from 'drizzle-orm';
import { DashboardHeader } from '@/components/dashboard/dashboard-header';
import { EnhancedBookingCalendar } from '@/components/booking/enhanced-booking-calendar';
import { UserBookingManagement } from '@/components/booking/user-booking-management';
import { getAppConfig } from '@/lib/app-config';

export default async function DashboardPage() {
	const config = await getAppConfig();
	const session = await getSession();

	if (!session) {
		redirect('/login');
	}

	// Get full user information
	const [user] = await db
		.select({
			id: users.id,
			email: users.email,
			name: users.name,
			surname: users.surname,
			role: users.role,
		})
		.from(users)
		.where(eq(users.id, session.userId))
		.limit(1);

	if (!user) {
		redirect('/login');
	}

	const userWithSession = {
		...session,
		name: user.name,
		surname: user.surname,
	};

	return (
		<div className='min-h-screen bg-background'>
			<DashboardHeader user={userWithSession} />

			<main className='container mx-auto px-4 py-8'>
				<div className='grid gap-8 lg:grid-cols-3'>
					{/* Main Content */}
					<div className='lg:col-span-2 space-y-6'>
						<div>
							<h1 className='text-3xl font-bold text-foreground mb-2'>
								Welcome back,{' '}
								{user.name && user.surname ? `${user.name} ${user.surname}` : user.email.split('@')[0]}!
								🏓
							</h1>
							<p className='text-muted-foreground'>
								Book your {config.sportName.toLowerCase()} court and enjoy your game
							</p>
						</div>

						<EnhancedBookingCalendar />
					</div>

					{/* Sidebar */}
					<div className='space-y-6'>
						<UserBookingManagement />
					</div>
				</div>
			</main>
		</div>
	);
}
