'use server';

import React, { Suspense } from 'react';

import { loadAnalyses } from '@/app/home/(user)/_lib/server/load-analyses';
import {
  loadCurrentUserAccount,
  loadUserAccount,
} from '@/app/home/(user)/_lib/server/load-user-account';
import { AnalysisResultDetails } from '@/packages/features/doctor/src/lib/server/schema/doctor-analysis-detail-view.schema';
import { createUserAnalysesApi } from '@/packages/features/user-analyses/src/server/api';
import { getSupabaseServerClient } from '@/packages/supabase/src/clients/server-client';

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

import AnalysisFallback from './analysis-fallback';
import NewAnalysisRecommendationsLoader from './new-analysis-recommendations-loader';

async function PrepareAIParameters({
  analysisResultDetails,
}: {
  analysisResultDetails: AnalysisResultDetails;
}) {
  const { analyses } = await loadAnalyses();
  const { account: doctorAccount } = await loadCurrentUserAccount();
  const patientAccount = await loadUserAccount(
    analysisResultDetails.patient.userId,
  );
  const client = getSupabaseServerClient();
  const userAnalysesApi = createUserAnalysesApi(client);
  const analysisResponses = await userAnalysesApi.getAllUserAnalysisResponses(
    patientAccount.id,
  );
  const currentAIResponseTimestamp = getLatestResponseTime(analysisResponses);

  return (
    <Suspense
      fallback={
        <AnalysisFallback progress={66} progressTextKey="doctor:loadFeedback" />
      }
    >
      <NewAnalysisRecommendationsLoader
        account={doctorAccount}
        currentAIResponseTimestamp={currentAIResponseTimestamp}
        analysisResponses={analysisResponses}
        analysisResultDetails={analysisResultDetails}
        analyses={analyses}
        patient={patientAccount}
      />
    </Suspense>
  );
}

export default withI18n(PrepareAIParameters);
