import { getSupabaseServerClient } from '@kit/supabase/server-client';
import { createMeetingsApi } from '@kit/sitzungsprotokolle/api';
import { MeetingsTabNavigation, MeetingsDashboard } from '@kit/sitzungsprotokolle/components';

import { CmsPageShell } from '~/components/cms-page-shell';
import { AccountNotFound } from '~/components/account-not-found';

interface PageProps {
  params: Promise<{ account: string }>;
}

export default async function MeetingsPage({ params }: PageProps) {
  const { account } = await params;
  const client = getSupabaseServerClient();

  const { data: acct } = await client
    .from('accounts')
    .select('id')
    .eq('slug', account)
    .single();

  if (!acct) return <AccountNotFound />;

  const api = createMeetingsApi(client);

  let stats = { totalProtocols: 0, thisYearProtocols: 0, openTasks: 0, overdueTasks: 0 };
  let recentProtocols: Awaited<ReturnType<typeof api.getRecentProtocols>> = [];
  let overdueTasks: Awaited<ReturnType<typeof api.getOverdueTasks>> = [];

  try {
    [stats, recentProtocols, overdueTasks] = await Promise.all([
      api.getDashboardStats(acct.id),
      api.getRecentProtocols(acct.id),
      api.getOverdueTasks(acct.id),
    ]);
  } catch (e) {
    // Supabase query failed — render with empty data instead of crashing
    console.error('Failed to load meetings dashboard:', e);
  }

  return (
    <CmsPageShell account={account} title="Sitzungsprotokolle">
      <MeetingsTabNavigation account={account} activeTab="overview" />
      <MeetingsDashboard
        stats={stats}
        recentProtocols={recentProtocols}
        overdueTasks={overdueTasks}
        account={account}
      />
    </CmsPageShell>
  );
}
