import { getSupabaseServerClient } from '@kit/supabase/server-client';
import { createVerbandApi } from '@kit/verbandsverwaltung/api';
import {
  VerbandTabNavigation,
  CrossOrgMemberSearch,
} 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<{
    q?: string;
    status?: string;
    accountId?: string;
    page?: string;
  }>;
}

export default async function CrossOrgMembersPage({
  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, hierarchy] = await Promise.all([
    api.searchMembersAcrossHierarchy(acct.id, {
      search: sp.q,
      status: sp.status,
      accountId: sp.accountId,
      page,
      pageSize,
    }),
    api.getHierarchyTree(acct.id),
  ]);

  // Build flat list of child accounts for the filter dropdown
  const childAccounts: Array<{ id: string; name: string }> = [];

  function collectChildren(node: {
    id: string;
    name: string;
    children?: unknown[];
  }) {
    if (node.id !== acct!.id) {
      childAccounts.push({ id: node.id, name: node.name });
    }

    if (Array.isArray(node.children)) {
      for (const child of node.children) {
        collectChildren(
          child as { id: string; name: string; children?: unknown[] },
        );
      }
    }
  }

  collectChildren(hierarchy);

  return (
    <CmsPageShell
      account={account}
      title="Verbandsverwaltung - Mitgliedersuche"
      description="Suchen Sie Mitglieder in allen verknüpften Organisationen"
    >
      <VerbandTabNavigation account={account} activeTab="members" />
      <CrossOrgMemberSearch
        account={account}
        members={result.data}
        total={result.total}
        page={page}
        pageSize={pageSize}
        childAccounts={childAccounts}
      />
    </CmsPageShell>
  );
}
