import Link from 'next/link';

import { createI18nServerInstance } from '@/lib/i18n/i18n.server';
import { withI18n } from '@/lib/i18n/with-i18n';

import { Trans } from '@kit/ui/makerkit/trans';
import { PageBody } from '@kit/ui/page';
import { Button } from '@kit/ui/shadcn/button';

import { loadUserAnalysis } from '../../_lib/server/load-user-analysis';
import Analysis from './_components/analysis';
import pathsConfig from '~/config/paths.config';
import { redirect } from 'next/navigation';
import { getOrders } from '~/lib/services/order.service';
import { getAnalysisElements } from '~/lib/services/analysis-element.service';
import { loadCurrentUserAccount } from '@/app/home/(user)/_lib/server/load-user-account';
import { createPageViewLog } from '~/lib/services/audit/pageView.service';

export const generateMetadata = async () => {
  const i18n = await createI18nServerInstance();
  const title = i18n.t('analysis-results:pageTitle');

  return {
    title,
  };
};

async function AnalysisResultsPage() {
  const account = await loadCurrentUserAccount()
  if (!account) {
    throw new Error('Account not found');
  }

  const analysisResponses = await loadUserAnalysis();
  const analysisResponseElements = analysisResponses?.flatMap(({ elements }) => elements);

  const orders = await getOrders().catch(() => null);

  if (!orders) {
    redirect(pathsConfig.auth.signIn);
  }

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

  const analysisElementIds = [
    ...new Set(orders?.flatMap((order) => order.analysis_element_ids).filter(Boolean) as number[]),
  ];
  const analysisElements = await getAnalysisElements({ ids: analysisElementIds });
  const analysisElementsWithResults = analysisResponseElements
    ?.sort((a, b) => {
      if (!a.response_time || !b.response_time) {
        return 0;
      }
      return new Date(b.response_time).getTime() - new Date(a.response_time).getTime();
    })
    .map((results) => ({ results })) ?? [];
  const analysisElementsWithoutResults = analysisElements
    .filter((element) => !analysisElementsWithResults?.some(({ results }) => results.analysis_element_original_id === element.analysis_id_original));

  const hasNoAnalysisElements = analysisElementsWithResults.length === 0 && analysisElementsWithoutResults.length === 0;

  return (
    <PageBody>
      <div className="mt-8 flex flex-col sm:flex-row sm:items-center justify-between gap-4 sm:gap-0">
        <div>
          <h4>
            <Trans i18nKey="analysis-results:pageTitle" />
          </h4>
          <p className="text-muted-foreground text-sm">
            {analysisResponses && analysisResponses.length > 0 ? (
              <Trans i18nKey="analysis-results:description" />
            ) : (
              <Trans i18nKey="analysis-results:descriptionEmpty" />
            )}
          </p>
        </div>
        <Button asChild>
          <Link href={pathsConfig.app.orderAnalysisPackage}>
            <Trans i18nKey="analysis-results:orderNewAnalysis" />
          </Link>
        </Button>
      </div>
      <div className="flex flex-col gap-2">
        {analysisElementsWithResults.map(({ results }) => {
          const analysisElement = analysisElements.find((element) => element.analysis_id_original === results.analysis_element_original_id);
          if (!analysisElement) {
            return null;
          }
          return (
            <Analysis key={results.id} analysisElement={analysisElement} results={results} />
          );
        })}
        {analysisElementsWithoutResults.map((element) => (
          <Analysis key={element.analysis_id_original} analysisElement={element} />
        ))}
        {hasNoAnalysisElements && (
          <div className="text-muted-foreground text-sm">
            <Trans i18nKey="analysis-results:noAnalysisElements" />
          </div>
        )}
      </div>
    </PageBody>
  );
}

export default withI18n(AnalysisResultsPage);
