import React from 'react';

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

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 { 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';

export default async function AnalysisResultsPage({
  params,
}: {
  params: Promise<{
    id: string;
  }>;
}) {
  const { id: analysisOrderId } = await params;

  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,
  });

  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={`${analysisResponse.order.createdAt ? new Date(analysisResponse?.order?.createdAt).toLocaleString() : ''}`}
              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, index) => (
              <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>
    </>
  );
}
