import { redirect } from 'next/navigation';


import { createI18nServerInstance } from '~/lib/i18n/i18n.server';
import { withI18n } from '~/lib/i18n/with-i18n';
import { PageBody, PageHeader } from '@kit/ui/page';
import { Trans } from '@kit/ui/trans';
import { getSupabaseServerClient } from '@/packages/supabase/src/clients/server-client';
import { toTitleCase } from '@/lib/utils';

import Dashboard from '../_components/dashboard';

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

  return {
    title,
  };
};

async function UserHomePage() {
  const account = await getAccount();
  if (!account) {
    redirect('/');
  }

  return (
    <>
      <PageHeader title={
        <>
          <Trans i18nKey={'common:welcome'} />
          {account.name ? `, ${toTitleCase(account.name)}` : ''}
        </>
      }
        description={
          <Trans i18nKey={'dashboard:recentlyCheckedDescription'} />
        }
      />
      <PageBody>
        <Dashboard />
      </PageBody>
    </>
  );
}

async function getAccount() {
  const client = getSupabaseServerClient();
  
  const {
    data: { user },
  } = await client.auth.getUser();

  const accountResponse = await client
    .schema('medreport')
    .from('accounts')
    .select('name')
    .eq('primary_owner_user_id', user!.id)
    .single();

  return accountResponse.data;
}

export default withI18n(UserHomePage);
