"use client";

import { getServerSession } from "next-auth/next";
import { authOptions } from "@/app/api/auth/[...nextauth]/route";
import { redirect } from "next/navigation";
import { prisma } from "@/lib/prisma";
import { CalendarClient } from "@/components/calendar/calendar-client";

export const metadata = {
  title: "Enkun - Calendrier",
  description: "Gérez vos rendez-vous et événements",
};

export default async function CalendarPage() {
  const session = await getServerSession(authOptions);

  if (!session?.user) {
    redirect("/api/auth/signin");
  }

  // Get user's calendars
  const userCalendars = await prisma.calendar.findMany({
    where: {
      userId: session.user.username || session.user.email,
    },
    include: {
      events: {
        orderBy: {
          start: 'asc'
        }
      }
    },
    orderBy: {
      createdAt: "desc",
    },
  });

  // Create default calendar if none exists
  let calendars = userCalendars;
  if (calendars.length === 0) {
    const defaultCalendar = await prisma.calendar.create({
      data: {
        name: "Calendrier principal",
        color: "#0082c9",
        description: "Calendrier par défaut",
        userId: session.user.username || session.user.email,
      },
      include: {
        events: true
      }
    });
    calendars = [defaultCalendar];
  }

  return (
    <div className='container mx-auto py-8'>
      <div className='mb-6'>
        <h1 className='text-3xl font-bold'>Calendrier</h1>
        <p className='text-muted-foreground'>
          Gérez vos rendez-vous et événements
        </p>
      </div>
      <div className="bg-white rounded-lg shadow">
        <CalendarClient 
          initialCalendars={calendars} 
          userId={session.user.username || session.user.email}
        />
      </div>
    </div>
  );
}
