import { redirect } from 'next/navigation';

import { loadCurrentUserAccount } from '@/app/home/(user)/_lib/server/load-user-account';
import { signOutAction } from '@/lib/actions/sign-out';

import { BackButton } from '@kit/shared/components/back-button';
import { MedReportLogo } from '@kit/shared/components/med-report-logo';
import { pathsConfig } from '@kit/shared/config';
import { Trans } from '@kit/ui/trans';

import { withI18n } from '~/lib/i18n/with-i18n';
import { toTitleCase } from '~/lib/utils';

import { UpdateAccountForm } from './_components/update-account-form';

async function UpdateAccount() {
  const { account, user } = await loadCurrentUserAccount();

  const isKeycloakUser = user?.app_metadata?.provider === 'keycloak';
  const isEmailUser = user?.app_metadata?.provider === 'email';

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

  const defaultValues = {
    firstName: account?.name ? toTitleCase(account.name) : '',
    lastName: account?.last_name ? toTitleCase(account.last_name) : '',
    personalCode: account?.personal_code ?? '',
    email: (() => {
      if (isKeycloakUser) {
        return account?.email ?? '';
      }
      return account?.email ?? user?.email ?? '';
    })(),
    phone: account?.phone ?? '+372',
    city: account?.city ?? '',
    weight: account?.accountParams?.weight ?? null,
    height: account?.accountParams?.height ?? null,
    userConsent: account?.has_consent_personal_data ?? false,
  };

  return (
    <div className="border-border xs:w-3/5 flex w-9/10 flex-row overflow-hidden rounded-3xl border md:w-[988px]">
      <div className="xs:px-6 relative flex w-full flex-col pt-7 pb-22 text-center md:w-1/2 md:px-12">
        <BackButton onBack={signOutAction} />
        <MedReportLogo />
        <h1 className="pt-8">
          <Trans i18nKey={'account:updateAccount:title'} />
        </h1>
        <p className="text-muted-foreground pt-1 text-sm">
          <Trans i18nKey={'account:updateAccount:description'} />
        </p>
        <UpdateAccountForm
          defaultValues={defaultValues}
          isEmailUser={isEmailUser}
        />
      </div>
      <div className="hidden w-1/2 bg-[url(/assets/med-report-logo-big.png)] bg-cover bg-center bg-no-repeat md:block"></div>
    </div>
  );
}

export default withI18n(UpdateAccount);
