import { getSupabaseServerClient } from '@kit/supabase/server-client';
import { createVerbandApi } from '@kit/verbandsverwaltung/api';
import {
  VerbandTabNavigation,
  HierarchyEvents,
} from '@kit/verbandsverwaltung/components';

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

interface PageProps {
  params: Promise<{ account: string }>;
  searchParams: Promise<{
    status?: string;
    sharedOnly?: string;
    fromDate?: string;
    page?: string;
  }>;
}

export default async function HierarchyEventsPage({
  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 = createVerbandApi(client);
  const page = Math.max(1, Number(sp.page) || 1);
  const pageSize = 25;

  const result = await api.listHierarchyEvents(acct.id, {
    status: sp.status,
    sharedOnly: sp.sharedOnly === 'true',
    fromDate: sp.fromDate,
    page,
    pageSize,
  });

  return (
    <CmsPageShell
      account={account}
      title="Verbandsverwaltung - Veranstaltungen"
      description="Veranstaltungen aller verknüpften Organisationen anzeigen und filtern"
    >
      <VerbandTabNavigation account={account} activeTab="events" />
      <HierarchyEvents
        account={account}
        events={result.data}
        total={result.total}
        page={page}
        pageSize={pageSize}
      />
    </CmsPageShell>
  );
}
