import React from 'react';
import PropTypes from 'prop-types';

import useTranslate from '~hooks/useTranslate/useTranslate';
import { defaultStats } from '../../../constants/statistics-counter.js';
import { generateLabel, getObjectValue } from '../../../helpers/info-grid';
import { getStart } from '../../../helpers/statistics-counter';
import styles from './statistics-counter.module.scss';

const StatisticsCounter = ({ page, module }) => {
  const { template } = page;

  module = {
    ...module,
    siteSchema: page?.siteSchema,
  };

  const statistics = defaultStats[template] || Object.values(defaultStats)[0];

  return (
    <div className={styles.statisticsCounter}>
      {statistics?.map((stat) => {
        const {
          fieldLabel,
          fieldLabelTranslationKey,
          fieldLabelIcon,
          fieldValue,
          fieldValueFn,
          componentToUse,
          fieldValueText,
          fieldValueTranslationKey,
          fieldValueIcon,
        } = stat;

        const value =
          generateLabel(
            fieldLabelTranslationKey,
            getObjectValue(module, fieldValue),
            fieldValueFn,
            {}
          ) || '-';

        // eslint-disable-next-line no-restricted-globals
        const updatedVal = isNaN(value) ? 0 : value;
        const component = componentToUse ? componentToUse(updatedVal, getStart(updatedVal)) : false;

        return (
          <div className={styles.gridItem || ''}>
            <p>
              {useTranslate(fieldLabelTranslationKey, fieldLabel)}
              {fieldLabelIcon && fieldLabelIcon}
            </p>
            <p>
              {component || value}
              {fieldValueText && (
                <span>{useTranslate(fieldValueTranslationKey, fieldValueText)}</span>
              )}
              {fieldValueIcon && fieldValueIcon}
            </p>
          </div>
        );
      })}
    </div>
  );
};

StatisticsCounter.propTypes = {
  page: PropTypes.shape({
    template: PropTypes.string,
    market: PropTypes.string,
    siteSchema: PropTypes.shape({}),
  }),
  module: PropTypes.shape({
    siteSchema: PropTypes.shape({}),
  }),
};

export default StatisticsCounter;
