import React from 'react';

import Link from 'next/link';
import { redirect } from 'next/navigation';

import { createNotificationsApi } from '@/packages/features/notifications/src/server/api';
import { getSupabaseServerClient } from '@/packages/supabase/src/clients/server-client';

import { ButtonTooltip } from '@kit/shared/components/ui/button-tooltip';
import { pathsConfig } from '@kit/shared/config';
import { Button } from '@kit/ui/button';
import { PageBody, PageHeader } from '@kit/ui/page';
import { Trans } from '@kit/ui/trans';
import { formatDateAndTime } from '@kit/shared/utils';

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

import Analysis from '../_components/analysis';

async function AnalysisResultsPage({
  params,
}: {
  params: Promise<{
    id: string;
  }>;
}) {
  const supabaseClient = getSupabaseServerClient();
  const { id: analysisOrderId } = await params;
  const notificationsApi = createNotificationsApi(supabaseClient);

  const [{ account }, analysisResponse] = await Promise.all([
    loadCurrentUserAccount(),
    loadUserAnalysis(Number(analysisOrderId)),
  ]);

  if (!account?.id) {
    return redirect('/');
  }

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

  await notificationsApi.dismissNotification(
    `/home/analysis-results/${analysisOrderId}`,
    'link',
  );

  if (!analysisResponse) {
    return (
      <>
        <PageHeader
          title={<Trans i18nKey="analysis-results:pageTitle" />}
          description={<Trans i18nKey="analysis-results:descriptionEmpty" />}
        />
        <PageBody className="gap-4"></PageBody>
      </>
    );
  }

  const orderedAnalysisElements = analysisResponse.orderedAnalysisElements;
  const hasOrderedAnalysisElements = orderedAnalysisElements.length > 0;
  const isPartialStatus =
    analysisResponse.order.status === 'PARTIAL_ANALYSIS_RESPONSE';

  return (
    <>
      <PageHeader
        title={<Trans i18nKey="analysis-results:pageTitle" />}
        description={
          hasOrderedAnalysisElements ? (
            isPartialStatus ? (
              <Trans i18nKey="analysis-results:descriptionPartial" />
            ) : (
              <Trans i18nKey="analysis-results:description" />
            )
          ) : (
            <Trans i18nKey="analysis-results:descriptionEmpty" />
          )
        }
      >
        <div>
          <Button asChild>
            <Link href={pathsConfig.app.orderAnalysisPackage}>
              <Trans i18nKey="analysis-results:orderNewAnalysis" />
            </Link>
          </Button>
        </div>
      </PageHeader>
      <PageBody className="gap-4 pt-4">
        <div className="flex flex-col gap-4">
          <h5 className="break-all">
            <Trans
              i18nKey="analysis-results:orderTitle"
              values={{ orderNumber: analysisResponse.order.medusaOrderId }}
            />
          </h5>
          <h6>
            <Trans i18nKey={`orders:status.${analysisResponse.order.status}`} />
            <ButtonTooltip
              content={
                <Trans
                  i18nKey="analysis-results:orderCreatedAt"
                  values={{
                    createdAt: formatDateAndTime(analysisResponse.order.createdAt)
                  }}
                />
              }
              className="ml-6"
            />
          </h6>
        </div>
        {analysisResponse?.summary?.value && (
          <div>
            <strong>
              <Trans i18nKey="account:doctorAnalysisSummary" />
            </strong>
            <p>{analysisResponse.summary.value}</p>
          </div>
        )}
        <div className="flex flex-col gap-2">
          {orderedAnalysisElements ? (
            orderedAnalysisElements.map((element) => (
              <React.Fragment key={element.analysisIdOriginal}>
                <Analysis element={element} />
                {element.results?.nestedElements?.map(
                  (nestedElement, nestedIndex) => (
                    <Analysis
                      key={`nested-${nestedElement.analysisElementOriginalId}-${nestedIndex}`}
                      nestedElement={nestedElement}
                      isNestedElement
                    />
                  ),
                )}
              </React.Fragment>
            ))
          ) : (
            <div className="text-muted-foreground text-sm">
              <Trans i18nKey="analysis-results:noAnalysisElements" />
            </div>
          )}
        </div>
      </PageBody>
    </>
  );
}

export default withI18n(AnalysisResultsPage);
