import { Suspense, cache } from 'react';

import { getAnalysisResultsForDoctor } from '@kit/doctor/services/doctor-analysis.service';
import { PageBody, PageHeader } from '@kit/ui/page';

import { withI18n } from '~/lib/i18n/with-i18n';
import {
  DoctorPageViewAction,
  createDoctorPageViewLog,
} from '~/lib/services/audit/doctorPageView.service';

import AnalysisFallback from '../../_components/analysis-fallback';
import { DoctorGuard } from '../../_components/doctor-guard';
import PrepareAiParameters from '../../_components/prepare-ai-parameters';

async function AnalysisPage({
  params,
}: {
  params: Promise<{
    id: string;
  }>;
}) {
  const { id: analysisOrderId } = await params;
  const analysisResultDetails = await loadResult(Number(analysisOrderId));

  if (!analysisResultDetails) {
    return null;
  }

  if (analysisResultDetails) {
    await createDoctorPageViewLog({
      action: DoctorPageViewAction.VIEW_ANALYSIS_RESULTS,
      recordKey: analysisOrderId,
      dataOwnerUserId: analysisResultDetails.patient.userId,
    });
  }

  return (
    <>
      <PageHeader />
      <PageBody className="px-12">
        <Suspense
          fallback={
            <AnalysisFallback
              progress={33}
              progressTextKey="doctor:loadParameters"
            />
          }
        >
          <PrepareAiParameters analysisResultDetails={analysisResultDetails} />
        </Suspense>
      </PageBody>
    </>
  );
}

export default DoctorGuard(withI18n(AnalysisPage));
const loadResult = cache(getAnalysisResultsForDoctor);
