import type { SelectedAnalyticsReferrers } from '~/src/store/dashboard/selectors/analytics';

import Box from '~/src/components/Box';
import PageLoading from '~/src/components/PageLoading';
import Text from '~/src/components/Text';
import useTheme from '~/src/hooks/useTheme';
import { resolveServiceDataFromUrl } from '~/src/lib/getServiceDisplayData';
import { useI18n } from '~/src/lib/i18n';
import HorizontalBarChart from './HorizontalBarChart';

/**
 * Groups items by name and sums their totals to avoid duplication:
 * https://theorchard.atlassian.net/browse/AD-842
 *
 * We have to stick to this solution right now, but in the future
 * a better solution would be to have a sublist on every item
 * that has multiple origins, so the user can expand the item
 * and see more detailed data. We would use the name as label for
 * the main list, and url as label for the sublist.
 */
function groupByName(items: { total: number; url: string }[]) {
  const data = items.map((item) => {
    const { url, total } = item;
    const { name } = resolveServiceDataFromUrl(url);
    return { name, total, url };
  });

  return Object.values(
    data.reduce(
      (acc, item) => {
        if (!acc[item.name]) {
          acc[item.name] = { name: item.name, total: 0, url: item.url };
        }

        acc[item.name].total += item.total;
        return acc;
      },
      {} as Record<string, (typeof data)[0]>
    )
  );
}

const SessionsByReferrer = ({
  data,
}: {
  data?: SelectedAnalyticsReferrers;
}) => {
  const { t } = useI18n('dashboard');
  const theme = useTheme();

  const chartItems = groupByName(data?.items ?? []).map(
    ({ total, url, name }) => {
      const { Icon, color } = resolveServiceDataFromUrl(url);
      const text = url !== 'unknown' ? name || url : name;

      return {
        detailText: t('totalVisitsFrom', { total, source: url }),
        color,
        label: (
          <>
            <Icon size="1.3em" isInline margin="0 0.5em 0 0" />
            <Text isInline isBold size="0.9em">
              {text}
            </Text>
          </>
        ),
        total,
      };
    }
  );

  return (
    <Box testId="dashboardTrafficChart" positionRelative>
      {(() => {
        if (!data?.items) return <PageLoading />;

        return (
          <>
            <Text isBold centered size="1.5em" color={theme.textColor90}>
              {t('trafficSources')}
            </Text>
            <Text
              size="0.9em"
              color={theme.textColor40}
              centered
              margin="0.4em 0 2em"
            >
              {t('trafficSourcesHelp')}
            </Text>
            <HorizontalBarChart items={chartItems!} total={data.total} />
          </>
        );
      })()}
    </Box>
  );
};

export default SessionsByReferrer;
