import differenceInHours from 'date-fns/differenceInHours';
import Stack from '@material-hu/mui/Stack';

import useFormatDate from 'src/hooks/useFormatDate';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { useArticleId } from '../../hooks/useArticleId';
import { type Article } from '../../types';
import { useGetArticleMetrics } from '../hooks/useGetArticleMetrics';
import { type MetricValue } from '../types';

import { Metric } from './Metric';
import { ReportCard } from './ReportCard';

type MetricsProps = {
  article: Article | undefined;
  loading: boolean;
};

export const ArticleMetrics = ({ article, loading }: MetricsProps) => {
  const { articleId } = useArticleId();
  const { formatDate } = useFormatDate();
  const { t } = useLokaliseTranslation('libraries');

  const {
    data: metrics,
    isLoading: metricsLoading,
    isError,
    isSuccess,
  } = useGetArticleMetrics(articleId);

  const showEmpty = isSuccess && !metrics;
  const showLoading = loading || metricsLoading;

  const startDate = metrics?.lastUpdate
    ? new Date(metrics?.lastUpdate)
    : undefined;

  const metricsItems: MetricValue[] = [
    {
      value: metrics?.totalViews ?? null,
      title: t('general:report.views.total'),
      tooltip: t('article.report.views.total'),
    },
    {
      value: metrics?.uniqueViews ?? null,
      title: t('general:report.views.unique'),
      tooltip: t('article.report.views.unique'),
    },
    {
      value: metrics?.totalAttachmentDownloads ?? null,
      title: t('general:report.attachment_download'),
      tooltip: t('article.report.attachment_download'),
    },
  ];

  const description = t('general:report.historical.since', {
    date: article?.createdAt ? formatDate(article.createdAt, 'PPP, p.') : '',
  });

  const descriptionTooltip = startDate
    ? t('general:report.last_update', {
        count: differenceInHours(new Date(), startDate) + 1,
      })
    : undefined;

  return (
    <ReportCard
      title={article?.title ?? ''}
      description={description}
      descriptionTooltip={descriptionTooltip}
      showEmpty={showEmpty}
      showError={isError}
      loading={showLoading}
    >
      <Stack sx={{ width: '100%', flexDirection: 'row', gap: 3 }}>
        {metricsItems.map((metric, index) => {
          const showDivider =
            metric.value !== null && metricsItems[index + 1]?.value !== null;

          return (
            <Metric
              key={metric.title}
              loading={showLoading}
              divider={showDivider}
              {...metric}
            />
          );
        })}
      </Stack>
    </ReportCard>
  );
};
