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

import { colors, metricColorsV2 } from '../Colors'
import { DateData } from '../DateData'
import { TextStyles } from '../Styles'
import { VideoFieldsFragment } from '../graphql/__generated__/sdk'
import { useEngagementSummary } from '../hooks/useVideoEngagement'
import { Strings } from '../i18n'
import { TimeInterval } from '../types/TimeInterval'
import { formatCountShort, timeRangeInterval } from '../util'
import { formatInterval } from '../util/date'
import { AutoLayout } from './AutoLayout'
import { DataTile } from './DataTile'
import { PercentPill } from './PercentPill'
import { BarFigure } from './figures/BarFigure'
import {
  engagementMetricIcons,
  engagementMetricLabels,
  engagementMetrics,
} from './videoEngagement'

/**
 * A row representing a video engagement metric
 */
const EngagementMetricRow: React.FC<{
  color: string
  icon: React.ReactNode
  label: string
  currentIntervalSum: number
  changePercentage: number | null
  currentValues: DateData<number | null>[]
  style?: StyleProp<ViewStyle>
}> = ({
  color,
  icon,
  label,
  currentIntervalSum,
  changePercentage,
  currentValues,
  style,
}) => {
  return (
    <View
      style={[
        {
          flexDirection: 'row',
          justifyContent: 'space-between',
          alignItems: 'center',
        },
        style,
      ]}
    >
      <AutoLayout
        style={{
          flex: 1,
          flexDirection: 'row',
          alignItems: 'center',
        }}
        gap={4}
      >
        <View>{icon}</View>
        <View>
          <Text style={[TextStyles.tiny, { color: colors.white }]}>
            {label}
          </Text>
        </View>
      </AutoLayout>

      <AutoLayout
        style={{
          flex: 2,
          flexDirection: 'row',
          justifyContent: 'flex-end',
          alignItems: 'center',
        }}
        gap={8}
      >
        <View style={{ width: 66, height: 15 }}>
          <MiniBarGraph values={currentValues} barColor={color} />
        </View>
        <View
          style={{
            flex: 1,
            alignItems: 'flex-end',
          }}
        >
          <Text style={[TextStyles.tiny, { color: colors.white }]}>
            {formatCountShort(currentIntervalSum)}
          </Text>
        </View>
        {changePercentage != null ? (
          <PercentPill
            style={{ minWidth: 48 }}
            size="small"
            percentage={changePercentage}
          />
        ) : (
          <View />
        )}
      </AutoLayout>
    </View>
  )
}

const MiniBarGraph: React.FC<{
  barColor: string
  values: DateData<number | null>[]
}> = ({ barColor, values }) => {
  return (
    <BarFigure
      data={values}
      style={{ width: 100, height: 15 }}
      barStyle={() => ({
        minHeight: 1,
        fill: barColor,
      })}
      barWidth={1}
      valueExtractor={(item) => item.data ?? 0}
      statusExtractor={() => 'full'} // Don't display "x" in this tiny graph
      rangeMin={0}
    />
  )
}

/**
 * A tile representing video engagement for a dsp
 */
export const VideoEngagementTile: React.FC<{
  video: VideoFieldsFragment
  timeInterval: TimeInterval
  countryCode?: string
  onPress: () => void
  style?: StyleProp<ViewStyle>
}> = ({ video, timeInterval, countryCode, onPress, style }) => {
  const videoId = video.id
  const currentInterval = timeRangeInterval(timeInterval)
  const summary = useEngagementSummary(videoId, currentInterval, countryCode)

  return (
    <DataTile
      dsp={video.dsp}
      title={Strings.Shared.Engagement}
      subTitle={formatInterval(currentInterval)}
      onPress={onPress}
      style={[{ minHeight: 253 }, style]}
      error={null}
    >
      {summary !== null ? (
        <View style={{ flex: 1 }}>
          <AutoLayout gap={12} style={{ flexDirection: 'column' }}>
            {engagementMetrics.map((metric) => {
              const Icon = engagementMetricIcons[metric]
              return (
                <EngagementMetricRow
                  key={metric}
                  color={metricColorsV2[metric]}
                  icon={<Icon stroke={metricColorsV2[metric]} />}
                  label={engagementMetricLabels[metric]}
                  {...summary[metric]}
                />
              )
            })}
          </AutoLayout>
        </View>
      ) : null}
    </DataTile>
  )
}
