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

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

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

import StatisticsContent from './_components/statistics-content';

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

export default async function StatisticsPage({ params }: Props) {
  const { account } = await params;
  const t = await getTranslations('verband');
  const client = getSupabaseServerClient();

  const { data: acct } = await client
    .from('accounts')
    .select('id')
    .eq('slug', account)
    .single();

  if (!acct) return <AccountNotFound />;

  // Fetch real verband stats
  const [clubsResult, membersResult, feesResult] = await Promise.allSettled([
    client
      .from('member_clubs')
      .select('id, status, member_count', { count: 'exact' })
      .eq('account_id', acct.id),
    client
      .from('members')
      .select('id', { count: 'exact' })
      .eq('account_id', acct.id)
      .eq('status', 'active'),
    (client.from as any)('club_fees')
      .select('amount, status')
      .eq('account_id', acct.id),
  ]);

  const clubs = clubsResult.status === 'fulfilled' ? (clubsResult.value.data ?? []) : [];
  const activeClubs = clubs.filter((c: any) => c.status !== 'archived').length;
  const totalMembers = clubsResult.status === 'fulfilled'
    ? clubs.reduce((sum: number, c: any) => sum + (Number(c.member_count) || 0), 0)
    : 0;
  const directMembers = membersResult.status === 'fulfilled' ? (membersResult.value.count ?? 0) : 0;
  const fees = feesResult.status === 'fulfilled' ? (feesResult.value.data ?? []) : [];
  const openFees = fees.filter((f: any) => f.status !== 'paid').reduce((s: number, f: any) => s + (Number(f.amount) || 0), 0);

  return (
    <CmsPageShell account={account} title={t('pages.statisticsTitle')}>
      <VerbandTabNavigation account={account} activeTab="statistics" />
      <StatisticsContent
        activeClubs={activeClubs}
        totalClubs={clubs.length}
        totalMembers={totalMembers || directMembers}
        openFees={openFees}
      />
    </CmsPageShell>
  );
}
