import { getTranslations } from 'next-intl/server';

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

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

import { InvitationsView } from './invitations-view';

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

export default async function InvitationsPage({ params }: Props) {
  const { account } = await params;
  const client = getSupabaseServerClient();
  const t = await getTranslations('members');
  const { data: acct } = await client
    .from('accounts')
    .select('id')
    .eq('slug', account)
    .single();
  if (!acct) return <AccountNotFound />;

  const { workflow } = createMemberServices(client);
  const invitations = await workflow.listPortalInvitations(acct.id);

  // Fetch members for the "send invitation" dialog
  const { data: members } = await client
    .from('members')
    .select('id, first_name, last_name, email')
    .eq('account_id', acct.id)
    .eq('status', 'active')
    .order('last_name');

  return (
    <CmsPageShell
      account={account}
      title={t('invitations.title')}
      description={t('invitations.subtitle')}
    >
      <InvitationsView
        invitations={invitations}
        members={members ?? []}
        accountId={acct.id}
        account={account}
      />
    </CmsPageShell>
  );
}
