import { PageBody } from '@kit/ui/page';
import { Trans } from '@kit/ui/trans';

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

import { HomeLayoutPageHeader } from '../../_components/home-page-header';
import OrderAnalysesCards from '../../_components/order-analyses-cards';
import { loadAnalyses } from '../../_lib/server/load-analyses';
import { loadCurrentUserAccount } from '../../_lib/server/load-user-account';

export const generateMetadata = async () => {
  const { t } = await createI18nServerInstance();

  return {
    title: t('order-analysis:title'),
  };
};

async function OrderAnalysisPage() {
  const { account } = await loadCurrentUserAccount();
  if (!account) {
    throw new Error('Account not found');
  }

  const { analyses, countryCode } = await loadAnalyses();

  await createPageViewLog({
    accountId: account.id,
    action: PageViewAction.VIEW_ORDER_ANALYSIS,
  });

  return (
    <>
      <HomeLayoutPageHeader
        title={<Trans i18nKey={'order-analysis:title'} />}
        description={<Trans i18nKey={'order-analysis:description'} />}
      />
      <PageBody>
        <OrderAnalysesCards analyses={analyses} countryCode={countryCode} />
      </PageBody>
    </>
  );
}

export default withI18n(OrderAnalysisPage);
