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

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

interface PageProps {
  params: Promise<{ account: string }>;
  searchParams: Promise<Record<string, string | string[] | undefined>>;
}

export default async function TasksPage({ params, searchParams }: PageProps) {
  const { account } = await params;
  const sp = await searchParams;
  const client = getSupabaseServerClient();

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

  if (!acct) return <AccountNotFound />;

  const api = createMeetingsApi(client);

  const page = typeof sp.page === 'string' ? parseInt(sp.page, 10) : 1;

  const result = await api.listOpenTasks(acct.id, { page });

  return (
    <CmsPageShell account={account} title="Sitzungsprotokolle">
      <MeetingsTabNavigation account={account} activeTab="tasks" />
      <div className="space-y-4">
        <div>
          <h1 className="text-2xl font-bold">Offene Aufgaben</h1>
          <p className="text-muted-foreground">
            Alle offenen und in Bearbeitung befindlichen Tagesordnungspunkte über alle Protokolle.
          </p>
        </div>
        <OpenTasksView
          data={result.data as any}
          total={result.total}
          page={result.page}
          pageSize={result.pageSize}
          account={account}
        />
      </div>
    </CmsPageShell>
  );
}
