import React from 'react'
import { StyleProp, ViewStyle } from 'react-native'

import { colors } from '../Colors'
import { Dsp } from '../Consts'
import { valuesForAllDatesInInterval } from '../DateData'
import {
  StreamsByDateResult,
  useEntityStreamsSummary,
} from '../hooks/useEntityStreams'
import { TimeInterval } from '../types/TimeInterval'
import { timeRangeInterval } from '../util'
import { formatInterval } from '../util/date'
import { DataTile } from './DataTile'
import { BottomRow } from './EntityStreamsTile2'
import { PercentPill } from './PercentPill'
import { BarAndLineFigure } from './figures/BarAndLineFigure'

/**
 * A tile representing entity (track/video) streams/views for a dsp
 */
export const EntityStreamsTile: React.FC<{
  dsp: Dsp | 'all'
  timeInterval: TimeInterval
  onPress: () => void
  style?: StyleProp<ViewStyle>
  useEntityStreams: (interval: Interval) => StreamsByDateResult
  title: string
  infoModalText?: string
  infoModalTitle?: string
  strokeColor?: string
}> = ({
  dsp,
  timeInterval,
  onPress,
  style,
  useEntityStreams,
  title,
  infoModalText,
  infoModalTitle,
  strokeColor,
}) => {
  const currentInterval = timeRangeInterval(timeInterval)
  const response = useEntityStreamsSummary(currentInterval, useEntityStreams)
  const summary = response?.data
  const error = response?.error
  const changePercentage = summary?.changePercentage ?? NaN

  return (
    <DataTile
      dsp={dsp}
      title={title}
      subTitle={formatInterval(currentInterval)}
      titleWidget={
        !isNaN(changePercentage) && (
          <PercentPill
            style={{ alignSelf: 'flex-end' }}
            percentage={changePercentage}
          />
        )
      }
      onPress={onPress}
      style={[{ minHeight: 340 }, style]}
      error={error ?? null}
      infoModalText={infoModalText}
      infoModalTitle={infoModalTitle}
    >
      {summary != null ? (
        <>
          <BarAndLineFigure
            plots={[
              {
                type: 'line',
                data: valuesForAllDatesInInterval(
                  summary.currentIntervalStreams,
                  currentInterval
                ),
                color: strokeColor ?? colors.offWhite,
                lineStrokeWidth: 2.5,
                axisSide: 'right',
              },
            ]}
            axisConfig={{
              right: {
                color: colors.offWhite,
              },
            }}
            grid
            valueExtractor={(item) => item.value}
          />
          <BottomRow total={summary.currentIntervalStreamsSum} />
        </>
      ) : null}
    </DataTile>
  )
}
