import React from 'react';

import { createUserAnalysesApi } from '@/packages/features/user-analyses/src/server/api';
import { getSupabaseServerClient } from '@/packages/supabase/src/clients/server-client';

import { PageBody } from '@kit/ui/makerkit/page';
import { Trans } from '@kit/ui/makerkit/trans';
import { Skeleton } from '@kit/ui/shadcn/skeleton';

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

import { HomeLayoutPageHeader } from '../../_components/home-page-header';
import { loadLifeStyle } from '../../_lib/server/load-life-style';
import { loadCurrentUserAccount } from '../../_lib/server/load-user-account';

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

  return {
    title: t('common:lifeStyle.title'),
  };
}

async function LifeStylePage() {
  const { account } = await loadCurrentUserAccount();
  if (!account) {
    return null;
  }
  const client = getSupabaseServerClient();
  const userAnalysesApi = createUserAnalysesApi(client);
  const analysisResponses = await userAnalysesApi.getAllUserAnalysisResponses();
  const currentAIResponseTimestamp = getLatestResponseTime(analysisResponses);
  const { response } = await loadLifeStyle({
    account,
    analysisResponses,
    aiResponseTimestamp: currentAIResponseTimestamp,
  });

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

  if (!response.lifestyle) {
    return <Skeleton className="mt-10 h-10 w-full" />;
  }

  return (
    <>
      <HomeLayoutPageHeader
        title={<Trans i18nKey={'common:lifeStyle.title'} />}
        description=""
      />

      <PageBody>
        <div className="mt-8">
          {response.lifestyle.map(({ title, description }, index) => (
            <React.Fragment key={`${index}-${title}`}>
              <div className="flex items-center gap-2">
                <h3>{title}</h3>
              </div>
              <p className="font-regular py-4">{description}</p>
            </React.Fragment>
          ))}
        </div>
      </PageBody>
    </>
  );
}

export default withI18n(LifeStylePage);
