import { drop } from 'lodash'
import React from 'react'
import { StyleProp, Text, View, ViewStyle } from 'react-native'

import { colors, DspColors } from '../Colors'
import { Dsp, StreamingDsp } from '../Consts'
import { valuesForAllDatesInInterval } from '../DateData'
import { TextStyles } from '../Styles'
import { IntervalSummary } from '../hooks/useEntityStreams'
import { NetworkError } from '../hooks/useNetwork'
import { Strings } from '../i18n'
import { TimeInterval } from '../types/TimeInterval'
import { DataWithStatus } from '../types/types'
import { formatCountShort, timeRangeInterval } from '../util'
import { formatInterval } from '../util/date'
import { DataTile } from './DataTile'
import { DspStreams } from './DspStreams'
import { PercentPill } from './PercentPill'
import { BarAndLineFigure, PlotConfig } from './figures/BarAndLineFigure'

export const LabelWithContent: React.FC<{
  label: string
}> = ({ label, children }) => (
  <View>
    <Text
      style={[
        TextStyles.tinyCaps,
        { color: colors.offWhite, textTransform: 'uppercase' },
      ]}
    >
      {label}
    </Text>
    {children}
  </View>
)

export const BottomRow: React.FC<{
  total: number
  currentValuePerDsp?:
    | {
        dsp: StreamingDsp
        streams: number
      }[]
    | null
  bottomRight?: React.ReactNode
}> = ({ total, currentValuePerDsp, bottomRight }) => {
  return (
    <View
      style={{
        flexDirection: 'column',
        justifyContent: 'space-between',
        marginTop: currentValuePerDsp ? 10 : 24,
      }}
    >
      {currentValuePerDsp && (
        <View
          style={{
            flexDirection: 'row',
            paddingBottom: 10,
          }}
        >
          {currentValuePerDsp.map(({ dsp, streams }) => (
            <DspStreams key={dsp} dsp={dsp} streams={streams} gap={5} />
          ))}
        </View>
      )}
      <View
        style={{
          alignItems: 'center',
          flexDirection: 'row',
          justifyContent: 'space-between',
        }}
      >
        <LabelWithContent label={Strings.Shared.Total}>
          <Text style={[TextStyles.h4, { color: colors.white }]}>
            {formatCountShort(total)}
          </Text>
        </LabelWithContent>
        {bottomRight}
      </View>
    </View>
  )
}

/**
 * A tile representing entity (track/video) streams/views for a dsp
 */
export const EntityStreamsTile2: React.FC<{
  dsp: Dsp | 'all'
  timeInterval: TimeInterval
  onPress: () => void
  style?: StyleProp<ViewStyle>
  summary?: IntervalSummary[]
  error?: NetworkError | null
  title: string
  infoModalText?: string
  infoModalTitle?: string
  strokeColor?: string
  bottomRight?: React.ReactNode
}> = ({
  dsp,
  timeInterval,
  onPress,
  style,
  summary,
  error,
  title,
  infoModalText,
  infoModalTitle,
  strokeColor,
  bottomRight,
}) => {
  const currentInterval = timeRangeInterval(timeInterval)
  const changePercentage = summary?.[0]?.changePercentage ?? NaN

  const plots: PlotConfig<DataWithStatus>[] =
    summary?.map((summary) => ({
      type: 'line',
      data: valuesForAllDatesInInterval(
        summary.currentIntervalStreams,
        currentInterval
      ),
      color: DspColors[summary.dsp ?? 'all'],
      lineStrokeWidth: 2.5,
      axisSide: 'right',
    })) ?? []

  const selectedDateStreamsPerDsp =
    dsp === 'all'
      ? drop(summary)?.map((sum) => ({
          dsp: sum.dsp as StreamingDsp,
          streams: sum.currentIntervalStreamsSum,
        }))
      : null

  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 && summary.length > 0 ? (
        <>
          <BarAndLineFigure
            plots={plots}
            axisConfig={{
              right: {
                color: colors.offWhite,
              },
            }}
            grid
            valueExtractor={(item) => item.value}
          />
          <BottomRow
            total={summary?.[0]?.currentIntervalStreamsSum}
            currentValuePerDsp={selectedDateStreamsPerDsp}
            bottomRight={bottomRight}
          />
        </>
      ) : null}
    </DataTile>
  )
}
