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

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

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

export default async function ProtocolsPage({
  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 search = typeof sp.q === 'string' ? sp.q : undefined;
  const meetingType = typeof sp.type === 'string' ? sp.type : undefined;
  const page = typeof sp.page === 'string' ? parseInt(sp.page, 10) : 1;

  const result = await api.listProtocols(acct.id, {
    search,
    meetingType,
    page,
  });

  return (
    <CmsPageShell account={account} title="Sitzungsprotokolle">
      <MeetingsTabNavigation account={account} activeTab="protocols" />
      <ProtocolsDataTable
        data={result.data}
        total={result.total}
        page={result.page}
        pageSize={result.pageSize}
        account={account}
      />
    </CmsPageShell>
  );
}
