import type { ReactNode } from 'react';

import { createMemberServices } from '@kit/member-management/services';
import { getSupabaseServerClient } from '@kit/supabase/server-client';

import { AccountNotFound } from '~/components/account-not-found';
import { TeamAccountLayoutPageHeader } from '~/home/[account]/_components/team-account-layout-page-header';

import { MembersCmsLayoutClient } from './_components/members-cms-layout-client';

interface Props {
  children: ReactNode;
  params: Promise<{ account: string }>;
}

export default async function MembersCmsLayout({ children, params }: Props) {
  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 { query } = createMemberServices(client);
  const stats = await query.getQuickStats(acct.id);

  return (
    <MembersCmsLayoutClient
      header={
        <TeamAccountLayoutPageHeader
          account={account}
          title="Mitglieder"
          description={`${stats.total} Mitglieder verwalten`}
        />
      }
      account={account}
      accountId={acct.id}
      stats={stats}
    >
      {children}
    </MembersCmsLayoutClient>
  );
}
