'use client';

import React, { useMemo, useState } from 'react';

import type {
  AnalysisResultDetailsElement,
  AnalysisResultsDetailsElementNested,
} from '@/packages/features/user-analyses/src/types/analysis-results';
import { AnalysisResultLevel } from '@/packages/features/user-analyses/src/types/analysis-results';
import { format } from 'date-fns';
import { Info } from 'lucide-react';
import { useTranslation } from 'react-i18next';

import { Trans } from '@kit/ui/trans';
import { cn } from '@kit/ui/utils';

import AnalysisLevelBar from './analysis-level-bar';

const Analysis = ({
  element: elementOriginal,
  nestedElement,
  isNestedElement = false,
}: {
  element?: AnalysisResultDetailsElement;
  nestedElement?: AnalysisResultsDetailsElementNested;
  isNestedElement?: boolean;
}) => {
  const { t } = useTranslation();

  const element = (() => {
    if (isNestedElement) {
      return nestedElement!;
    }
    return elementOriginal!;
  })();
  const results: AnalysisResultDetailsElement['results'] = useMemo(() => {
    if (isNestedElement) {
      const nestedElement = element as AnalysisResultsDetailsElementNested;
      return {
        analysisElementOriginalId: nestedElement.analysisElementOriginalId,
        normLower: nestedElement.normLower,
        normUpper: nestedElement.normUpper,
        normStatus: nestedElement.normStatus,
        responseTime: nestedElement.responseTime,
        responseValue: nestedElement.responseValue,
        responseValueIsNegative: nestedElement.responseValueIsNegative,
        responseValueIsWithinNorm: nestedElement.responseValueIsWithinNorm,
        normLowerIncluded: nestedElement.normLowerIncluded,
        normUpperIncluded: nestedElement.normUpperIncluded,
        unit: nestedElement.unit,
        status: nestedElement.status,
        nestedElements: [],
      };
    }
    return (element as AnalysisResultDetailsElement).results;
  }, [element, isNestedElement]);

  const name = element.analysisName || '';

  const hasIsWithinNorm = results?.responseValueIsWithinNorm !== null;
  const hasIsNegative = results?.responseValueIsNegative !== null;

  const value = (() => {
    if (!results) {
      return null;
    }

    const {
      responseValue,
      responseValueIsNegative,
      responseValueIsWithinNorm,
    } = results;
    if (responseValue === null || responseValue === undefined) {
      if (hasIsNegative) {
        if (responseValueIsNegative) {
          return t('analysis-results:results.value.negative');
        }
        return t('analysis-results:results.value.positive');
      }
      if (hasIsWithinNorm) {
        if (responseValueIsWithinNorm) {
          return t('analysis-results:results.value.isWithinNorm');
        }
        return t('analysis-results:results.value.isNotWithinNorm');
      }
      return null;
    }

    return responseValue;
  })();
  const unit = results?.unit || '';
  const normLower = results?.normLower ?? null;
  const normUpper = results?.normUpper ?? null;
  const normStatus = results?.normStatus ?? null;

  const [showTooltip, setShowTooltip] = useState(false);
  const analysisResultLevel = useMemo(() => {
    if (normStatus === null) {
      return null;
    }

    switch (normStatus) {
      case 1:
        return AnalysisResultLevel.WARNING;
      case 2:
        return AnalysisResultLevel.CRITICAL;
      case 0:
      default:
        return AnalysisResultLevel.NORMAL;
    }
  }, [normStatus]);

  const isCancelled = Number(results?.status) === 5;
  const nestedElements = results?.nestedElements ?? null;
  const hasNestedElements =
    Array.isArray(nestedElements) && nestedElements.length > 0;

  const normRangeText = (() => {
    if (normLower === null && normUpper === null) {
      return null;
    }
    return `${normLower ?? '...'} - ${normUpper ?? '...'}`;
  })();
  const hasTextualResponse = hasIsNegative || hasIsWithinNorm;

  return (
    <div
      className={cn('border-border rounded-lg border px-5', {
        'ml-8': isNestedElement,
      })}
    >
      <div className="flex flex-col items-center justify-between gap-2 pt-3 pb-6 sm:h-[65px] sm:flex-row sm:gap-0 sm:py-3">
        <div
          className={cn('flex items-center gap-2 font-semibold', {
            'font-bold': isNestedElement,
          })}
        >
          {name}
          {results?.responseTime && (
            <div
              className="group/tooltip relative"
              onClick={(e) => {
                e.stopPropagation();
                setShowTooltip(!showTooltip);
              }}
              onMouseLeave={() => setShowTooltip(false)}
            >
              <Info className="hover" />{' '}
              <div
                className={cn(
                  'absolute bottom-full left-1/2 z-10 mb-2 hidden -translate-x-1/2 rounded border bg-white p-4 text-sm whitespace-nowrap group-hover/tooltip:block',
                  { block: showTooltip },
                )}
              >
                <Trans i18nKey="analysis-results:analysisDate" />
                {': '}
                {format(new Date(results.responseTime), 'dd.MM.yyyy HH:mm')}
              </div>
            </div>
          )}
        </div>

        {isCancelled && (
          <div className="text-sm font-semibold text-red-600">
            <Trans i18nKey="analysis-results:cancelled" />
          </div>
        )}

        {isCancelled || !results || hasNestedElements ? null : (
          <>
            <div className="flex items-center gap-3 sm:ml-auto">
              <div
                className={cn('font-semibold', {
                  'text-yellow-600':
                    hasTextualResponse &&
                    analysisResultLevel === AnalysisResultLevel.WARNING,
                  'text-red-600':
                    hasTextualResponse &&
                    analysisResultLevel === AnalysisResultLevel.CRITICAL,
                  'text-green-600':
                    hasTextualResponse &&
                    analysisResultLevel === AnalysisResultLevel.NORMAL,
                })}
              >
                {value}
              </div>
              <div className="text-muted-foreground text-sm">{unit}</div>
            </div>
            {!hasTextualResponse && (
              <>
                <div className="text-muted-foreground mx-8 flex flex-col-reverse gap-2 text-center text-sm sm:block sm:gap-0">
                  {normRangeText}
                  <div>
                    <Trans i18nKey="analysis-results:results.range.normal" />
                  </div>
                </div>
                <AnalysisLevelBar
                  results={results}
                  level={analysisResultLevel!}
                  normRangeText={normRangeText}
                />
              </>
            )}
          </>
        )}
      </div>
    </div>
  );
};

export default Analysis;
