import { redirect } from 'next/navigation';

import { HomeLayoutPageHeader } from '@/app/home/(user)/_components/home-page-header';
import { loadCategory } from '@/app/home/(user)/_lib/server/load-category';

import { pathsConfig } from '@kit/shared/config';
import { AppBreadcrumbs } from '@kit/ui/makerkit/app-breadcrumbs';
import { Trans } from '@kit/ui/trans';

import BookingContainer from '~/home/(user)/_components/booking/booking-container';
import { loadCurrentUserAccount } from '~/home/(user)/_lib/server/load-user-account';
import { createI18nServerInstance } from '~/lib/i18n/i18n.server';
import { withI18n } from '~/lib/i18n/with-i18n';
import {
  PageViewAction,
  createPageViewLog,
} from '~/lib/services/audit/pageView.service';

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

  return {
    title,
  };
};

async function BookingHandlePage({
  params,
}: {
  params: Promise<{ handle: string }>;
}) {
  const { handle } = await params;
  const { category } = await loadCategory({ handle });
  const { account } = await loadCurrentUserAccount();

  if (!category) {
    return <div>Category not found</div>;
  }

  if (!account) {
    return redirect(pathsConfig.auth.signIn);
  }

  await createPageViewLog({
    accountId: account.id,
    action: PageViewAction.VIEW_TTO_SERVICE_BOOKING,
    extraData: {
      handle,
    },
  });

  return (
    <>
      <AppBreadcrumbs
        values={{
          [handle]: category?.name || handle,
        }}
      />
      <HomeLayoutPageHeader
        title={<Trans i18nKey={'booking:title'} />}
        description=""
      />

      <BookingContainer category={category} />
    </>
  );
}

export default withI18n(BookingHandlePage);
