'use server';

import React from 'react';

import { AnalysisResponses } from '@/app/home/(user)/_components/ai/types';
import { OrderAnalysisCard } from '@/app/home/(user)/_components/order-analyses-cards';
import { loadLifeStyle } from '@/app/home/(user)/_lib/server/load-life-style';
import { loadRecommendations } from '@/app/home/(user)/_lib/server/load-recommendations';
import { AccountWithParams } from '@/packages/features/accounts/src/types/accounts';
import { AnalysisResultDetails } from '@/packages/features/doctor/src/lib/server/schema/doctor-analysis-detail-view.schema';

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

import {
  loadDoctorFeedback,
  prepareFeedback,
} from '../_lib/server/load-doctor-feedback';
import AnalysisView from './analysis-view';

async function NewAnalysisRecommendationsLoader({
  analysisResultDetails,
  account,
  analysisResponses,
  currentAIResponseTimestamp,
  analyses,
  patient,
}: {
  currentAIResponseTimestamp: string;
  account: AccountWithParams | null;
  analysisResponses: AnalysisResponses;
  analysisResultDetails: AnalysisResultDetails;
  analyses: OrderAnalysisCard[];
  patient: AccountWithParams | null;
}) {
  if (!analysisResultDetails.order.isPackage) {
    return (
      <AnalysisView
        patient={analysisResultDetails.patient}
        order={analysisResultDetails.order}
        analyses={analysisResultDetails.analysisResponse}
        feedback={analysisResultDetails.doctorFeedback}
      />
    );
  }

  const [lifeStyle, recommendations, aiFeedback] = await Promise.all([
    loadLifeStyle({
      account: patient,
      analysisResponses,
      isDoctorView: true,
      aiResponseTimestamp: currentAIResponseTimestamp,
    }),
    loadRecommendations({
      account: patient,
      analysisResponses,
      aiResponseTimestamp: currentAIResponseTimestamp,
      isDoctorView: true,
      analyses,
    }),
    loadDoctorFeedback(
      analysisResultDetails.patient,
      analysisResultDetails.analysisResponse,
      currentAIResponseTimestamp,
    ),
  ]);

  const feedback = prepareFeedback({
    aiResponse: aiFeedback,
    recommendations,
    lifeStyleSummary: lifeStyle.response.summary,
    patientName: analysisResultDetails.patient.firstName,
    doctorName: `${account?.name} ${account?.last_name}`,
    aiResponseTimestamp: currentAIResponseTimestamp,
  });

  return (
    <AnalysisView
      patient={analysisResultDetails.patient}
      order={analysisResultDetails.order}
      analyses={analysisResultDetails.analysisResponse}
      feedback={analysisResultDetails.doctorFeedback}
      aiDoctorFeedback={feedback}
      availableAnalyses={analyses.map((analysis) => analysis.title)}
      recommendations={recommendations}
      timestamp={currentAIResponseTimestamp}
    />
  );
}

export default withI18n(NewAnalysisRecommendationsLoader);
