import { createMemberManagementApi } from '@kit/member-management/api';
import { MemberDetailView } from '@kit/member-management/components';
import { getSupabaseServerClient } from '@kit/supabase/server-client';

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

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

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

  const api = createMemberManagementApi(client);
  const member = await api.getMember(memberId);
  if (!member) return <AccountNotFound />;

  // Fetch sub-entities in parallel
  const [roles, honors, mandates] = await Promise.all([
    api.listMemberRoles(memberId),
    api.listMemberHonors(memberId),
    api.listMandates(memberId),
  ]);

  const memberName = `${String(member.first_name)} ${String(member.last_name)}`;

  return (
    <CmsPageShell
      account={account}
      title={memberName}
      breadcrumbValues={{ [memberId]: memberName }}
    >
      <MemberDetailView
        member={member}
        account={account}
        accountId={acct.id}
        roles={roles}
        honors={honors}
        mandates={mandates}
      />
    </CmsPageShell>
  );
}
