import { interpolateRgb } from 'd3-interpolate'
import React, { useRef, useEffect, useState } from 'react'
import { ViewStyle, StyleProp, Animated } from 'react-native'

import { colors } from '../Colors'

export const Bone: React.FC<{ style?: StyleProp<ViewStyle> }> = ({ style }) => {
  const backgroundColor = useFadingColor(
    colors.metals.metal2,
    colors.metals.metal1
  )
  const boneStyle = { backgroundColor, borderRadius: 4 }
  return <Animated.View style={[style, boneStyle]} />
}
type Color = string
function useFadingColor(from: Color, to: Color, duration = 500) {
  const fadeAnimation = useRef(new Animated.Value(0)).current
  const [color, setColor] = useState(from)

  useEffect(() => {
    const fadeOptions = { useNativeDriver: true, duration }
    const colorInterpolate = interpolateRgb(from, to)
    const listener = fadeAnimation.addListener(({ value }) =>
      setColor(colorInterpolate(value))
    )

    const { loop, sequence, timing } = Animated
    loop(
      sequence([
        timing(fadeAnimation, { ...fadeOptions, toValue: 1 }),
        timing(fadeAnimation, { ...fadeOptions, toValue: 0 }),
      ])
    ).start()

    return () => fadeAnimation.removeListener(listener)
  }, [fadeAnimation, from, to, duration])

  return color
}
