import { getServerSession } from "next-auth/next";
import { authOptions } from "@/app/api/auth/options";
import { redirect } from "next/navigation";
import { prisma } from "@/lib/prisma";
import { CalendarClient } from "@/components/calendar/calendar-client";
import { Metadata } from "next";
import { CalendarDays, Users, Bookmark, Clock } from "lucide-react";
import Image from "next/image";
import { Button } from "@/components/ui/button";
import { add } from 'date-fns';

export const metadata: Metadata = {
  title: "Enkun - Calendrier | Gestion d'événements professionnelle",
  description: "Plateforme avancée pour la gestion de vos rendez-vous, réunions et événements professionnels",
  keywords: "calendrier, rendez-vous, événements, gestion du temps, enkun",
};

interface Event {
  id: string;
  title: string;
  description?: string | null;
  start: Date;
  end: Date;
  location?: string | null;
  isAllDay: boolean;
  type?: string;
  attendees?: { id: string; name: string }[];
}

interface Calendar {
  id: string;
  name: string;
  color: string;
  description?: string | null;
  events: Event[];
}

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

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

  const userId = session.user.username || session.user.email || '';
  
  // Get all calendars for the user
  let calendars = await prisma.calendar.findMany({
    where: {
      userId: session?.user?.id || '',
    },
    include: {
      events: {
        orderBy: {
          start: 'asc'
        }
      }
    }
  });

  // If no calendars exist, create default ones
  if (calendars.length === 0) {
    const defaultCalendars = [
      {
        name: "Default",
        color: "#4F46E5",
        description: "Your default calendar"
      }
    ];

    calendars = await Promise.all(
      defaultCalendars.map(async (cal) => {
        return prisma.calendar.create({
          data: {
            ...cal,
            userId: session?.user?.id || '',
          },
          include: {
            events: true
          }
        });
      })
    );
  }

  const now = new Date();
  const nextWeek = add(now, { days: 7 });
  
  const upcomingEvents = calendars.flatMap(cal => 
    cal.events.filter(event => 
      new Date(event.start) >= now && 
      new Date(event.start) <= nextWeek
    )
  ).sort((a, b) => new Date(a.start).getTime() - new Date(b.start).getTime());

  // Calculate statistics
  const totalEvents = calendars.flatMap(cal => cal.events).length;
  
  const totalMeetingHours = calendars
    .flatMap(cal => cal.events)
    .reduce((total, event) => {
      const start = new Date(event.start);
      const end = new Date(event.end);
      const hours = (end.getTime() - start.getTime()) / (1000 * 60 * 60);
      return total + (isNaN(hours) ? 0 : hours);
    }, 0);

  return (
    <div className="container mx-auto py-10">
      <CalendarClient 
        initialCalendars={calendars} 
        userId={session.user.id}
        userProfile={{
          name: session.user.name || '',
          email: session.user.email || '',
          avatar: session.user.image || undefined
        }}
      />
    </div>
  );
}
