'use server';

import { use } from 'react';

import { CompanyGuard } from '@/packages/features/team-accounts/src/components';
import { createTeamAccountsApi } from '@/packages/features/team-accounts/src/server/api';
import { getSupabaseServerClient } from '@/packages/supabase/src/clients/server-client';

import { PageBody } from '@kit/ui/page';
import { createUserAnalysesApi } from '@kit/user-analyses/api';

import { createI18nServerInstance } from '~/lib/i18n/i18n.server';
import { withI18n } from '~/lib/i18n/with-i18n';
import {
  PageViewAction,
  createPageViewLog,
} from '~/lib/services/audit/pageView.service';

import { Dashboard } from './_components/dashboard';
import { loadAccountBenefitStatistics } from './_lib/server/load-team-account-benefit-statistics';

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

export const generateMetadata = async () => {
  const i18n = await createI18nServerInstance();
  const title = i18n.t('teams:home.pageTitle');

  return {
    title,
  };
};

function TeamAccountHomePage({ params }: TeamAccountHomePageProps) {
  const account = use(params).account;
  const client = getSupabaseServerClient();
  const teamAccountsApi = createTeamAccountsApi(client);
  const userAnalysesApi = createUserAnalysesApi(client);
  const teamAccount = use(teamAccountsApi.getTeamAccount(account));
  const { memberParams, members } = use(teamAccountsApi.getMembers(account));
  const bmiThresholds = use(userAnalysesApi.fetchBmiThresholds());
  const accountBenefitStatistics = use(loadAccountBenefitStatistics(teamAccount.id));

  use(
    createPageViewLog({
      accountId: teamAccount.id,
      action: PageViewAction.VIEW_TEAM_ACCOUNT_DASHBOARD,
    }),
  );

  return (
    <PageBody>
      <Dashboard
        teamAccount={teamAccount}
        memberParams={memberParams}
        bmiThresholds={bmiThresholds}
        members={members}
        accountBenefitStatistics={accountBenefitStatistics}
      />
    </PageBody>
  );
}

export default withI18n(CompanyGuard(TeamAccountHomePage));
