import { Suspense } from 'react';

import { redirect } from 'next/navigation';

import { toTitleCase } from '@/lib/utils';
import { getSupabaseServerClient } from '@/packages/supabase/src/clients/server-client';

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

import { createI18nServerInstance } from '~/lib/i18n/i18n.server';
import { withI18n } from '~/lib/i18n/with-i18n';

import Dashboard from '../_components/dashboard';
import DashboardCards from '../_components/dashboard-cards';
import Recommendations from '../_components/recommendations';
import RecommendationsSkeleton from '../_components/recommendations-skeleton';
import { isValidOpenAiEnv } from '../_lib/server/is-valid-open-ai-env';
import { loadCurrentUserAccount } from '../_lib/server/load-user-account';

export const generateMetadata = async () => {
  const i18n = await createI18nServerInstance();
  const title = i18n.t('account:homePage');

  return {
    title,
  };
};

async function UserHomePage() {
  const client = getSupabaseServerClient();

  const { account } = await loadCurrentUserAccount();
  const api = createUserAnalysesApi(client);
  const bmiThresholds = await api.fetchBmiThresholds();

  if (!account) {
    redirect('/');
  }

  return (
    <>
      <DashboardCards />
      <PageHeader
        title={
          <>
            <Trans i18nKey={'common:welcome'} />
            {account.name ? `, ${toTitleCase(account.name)}` : ''}
          </>
        }
        description={<Trans i18nKey={'dashboard:recentlyCheckedDescription'} />}
      />
      <PageBody>
        <Dashboard account={account} bmiThresholds={bmiThresholds} />
        {(await isValidOpenAiEnv()) && (
          <>
            <h4>
              <Trans i18nKey="dashboard:recommendations.title" />
            </h4>
            <Suspense fallback={<RecommendationsSkeleton />}>
              <Recommendations account={account} />
            </Suspense>
          </>
        )}
      </PageBody>
    </>
  );
}

export default withI18n(UserHomePage);
