import { Fragment } from 'react';
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, { AnalysisStatus } from './_components/analysis';

export const generateMetadata = async () => {
  const i18n = await createI18nServerInstance();
  const title = i18n.t('account:analysisResults.pageTitle');

  return {
    title,
  };
};

async function AnalysisResultsPage() {
  const analysisList = await loadUserAnalysis();

  return (
    <PageBody>
      <div className="mt-8 flex items-center justify-between">
        <div>
          <h4>
            <Trans i18nKey="account:analysisResults.pageTitle" />
          </h4>
          <p className="text-muted-foreground text-sm">
            {analysisList && analysisList.length > 0 ? (
              <Trans i18nKey="account:analysisResults.description" />
            ) : (
              <Trans i18nKey="account:analysisResults.descriptionEmpty" />
            )}
          </p>
        </div>
        <Button>
          <Trans i18nKey="account:analysisResults.orderNewAnalysis" />
        </Button>
      </div>
      <div className="flex flex-col gap-2">
        {analysisList?.map((analysis) => (
          <Fragment key={analysis.id}>
            {analysis.elements.map((element) => (
              <Analysis
                key={element.id}
                analysis={{
                  name: element.analysis_name || '',
                  status: element.norm_status as AnalysisStatus,
                  unit: element.unit || '',
                  value: element.response_value,
                  normLowerIncluded: !!element.norm_lower_included,
                  normUpperIncluded: !!element.norm_upper_included,
                  normLower: element.norm_lower || 0,
                  normUpper: element.norm_upper || 0,
                }}
              />
            ))}
          </Fragment>
        ))}
      </div>
    </PageBody>
  );
}

export default withI18n(AnalysisResultsPage);
