import { Metadata } from 'next';
import { DailyPageClient } from './DailyPageClient';
import { dailyService } from '@/services/task-management/daily';
import { DeadlineAnalyticsService } from '@/services/analytics/deadline-analytics';
import { getToday } from '@/lib/date-utils';
import { getServerSession } from 'next-auth/next';
import { authOptions } from '@/lib/auth';

// Force dynamic rendering (no static generation)
export const dynamic = 'force-dynamic';

export const metadata: Metadata = {
  title: 'Daily - Tower Control',
  description: 'Gestion quotidienne des tâches et objectifs',
};

export default async function DailyPage() {
  // Récupérer la session utilisateur
  const session = await getServerSession(authOptions);

  if (!session?.user?.id) {
    return (
      <div className="min-h-screen bg-[var(--background)] flex items-center justify-center">
        <div className="text-center">
          <h1 className="text-2xl font-bold text-[var(--foreground)] mb-4">
            Non autorisé
          </h1>
          <p className="text-[var(--muted-foreground)]">
            Vous devez être connecté pour accéder à la page daily.
          </p>
        </div>
      </div>
    );
  }

  // Récupérer les données côté serveur
  const today = getToday();

  try {
    const [
      dailyView,
      dailyDates,
      deadlineDatesMap,
      deadlineMetrics,
      pendingTasks,
    ] = await Promise.all([
      dailyService.getDailyView(today, session.user.id),
      dailyService.getDailyDates(session.user.id),
      dailyService.getTaskDeadlineDates(session.user.id).catch(() => ({})), // Graceful fallback
      DeadlineAnalyticsService.getDeadlineMetrics(session.user.id).catch(
        () => null
      ), // Graceful fallback
      dailyService
        .getPendingCheckboxes({
          maxDays: 7,
          excludeToday: true,
          limit: 50,
          userId: session.user.id,
        })
        .catch(() => []), // Graceful fallback
    ]);

    return (
      <DailyPageClient
        initialDailyView={dailyView}
        initialDailyDates={dailyDates}
        initialDeadlineDates={deadlineDatesMap}
        initialDate={today}
        initialDeadlineMetrics={deadlineMetrics}
        initialPendingTasks={pendingTasks}
      />
    );
  } catch (error) {
    console.error('Erreur SSR Daily:', error);
    // Fallback vers client-side rendering
    return <DailyPageClient />;
  }
}
