import React, { useMemo } from 'react'

import SparkLineWithTooltip from '../Charts/SparkLine/SparkLineWithTooltip'
import { useMediaQuery } from '../../hooks/responsiveHooks'
import Header from './Header'
import ChangeMetric from './ComparisonMetric'
import ContextualMetrics from './ContextualMetrics'
import MetricsSummary from './MetricsSummary'
import { type ScoreCardProps } from './ScoreCardType'
import styles from './_score-card.module.scss'

const ScoreCard = ({
  containerClassName = '',
  header,
  changeMetric,
  sparklineGraph,
  contextualMetrics,
  metricsSummary,
  loading = false,
  backgroundColor = 'white',
  noBorder = false,
  qaTestId = 'score-card',
}: ScoreCardProps) => {
  const isMobileView = useMediaQuery({ type: 'max', breakpoint: 'md' })

  const parentContainerStyles = {
    ...(backgroundColor
      ? { backgroundColor: `var(--${backgroundColor})` }
      : {}),
  }

  // SparklineWithTooltip only uses standard chart colors
  const sparklineGraphColor = useMemo(
    () =>
      changeMetric?.change
        ? changeMetric.change < 0
          ? 'red'
          : 'green'
        : 'blue',
    [changeMetric?.change],
  )

  return (
    <div
      className={`${styles.parentContainer} ${noBorder ? styles.parentContainerWithoutBorder : ''} ${containerClassName}`}
      style={parentContainerStyles}
      qa-test-id={qaTestId}
    >
      <div className={styles.topMetricsContainer}>
        {/* Title and subtitle section on header */}
        <Header {...header} />

        {/* Primary Metric with change value section */}
        <div className={styles.primaryMetricContainer}>
          <ChangeMetric {...changeMetric} loading={loading} />
          {sparklineGraph ? (
            <div className={styles.sparklineContentSection}>
              {sparklineGraph?.graphData ? (
                <SparkLineWithTooltip
                  {...sparklineGraph}
                  sparklineContainerDimension={{
                    // Ensures the sparkline graph isn't cut off on mobile
                    width: isMobileView ? window.innerWidth - 36 : 240,
                  }}
                  graphColor={sparklineGraphColor}
                />
              ) : (
                <div className={styles.sparklinePlaceholder} />
              )}
            </div>
          ) : null}
        </div>

        {/* Contextual Metric section */}
      </div>
      <div>
        {contextualMetrics ? (
          <ContextualMetrics {...contextualMetrics} loading={loading} />
        ) : null}
        {/* Optional Metric Summary with details link */}
        {metricsSummary ? (
          <MetricsSummary
            {...metricsSummary}
            backgroundColor={backgroundColor}
            loading={loading}
          />
        ) : null}
      </div>
    </div>
  )
}

export default ScoreCard
