import { LinearGradient } from 'expo-linear-gradient'
import { identity, memoize } from 'lodash'
import React from 'react'
import { StyleProp, ViewStyle, View } from 'react-native'

import { mod, hash } from '../util'

const hueStart = 195
const hueStop = 310
const hueOffset = 100
const hueMax = 360
const hueRange = hueStop - hueStart
const stringToHue = (s: string) =>
  mod(hash(s.split('').reverse().join('')), hueRange) + hueStart

const stringToColors = memoize((s = '') => {
  const baseHue = stringToHue(s)
  return [-hueOffset, 0, hueOffset]
    .map((offset) => mod(baseHue + offset, hueMax))
    .map((hue) => `hsl(${hue}, 100%, 50%)`)
}, identity)

export function ImageGradientBackground({
  string: isrc,
  style,
}: {
  string: string
  style?: StyleProp<ViewStyle>
}): React.ReactElement {
  return (
    <View style={style}>
      <LinearGradient
        colors={stringToColors(isrc)}
        locations={[0.0, 0.7, 1.0]}
        start={[0, 1]}
        end={[2.1, -1.2]}
        style={[
          {
            position: 'absolute',
            left: 0,
            right: 0,
            top: 0,
            bottom: 0,
            borderRadius: 4,
          },
        ]}
      />
    </View>
  )
}
