import {LinearGradient} from 'tuya-panel-kit'
import React, {useEffect} from 'react'
import {Rect} from 'react-native-svg'
import {StyleProp, View} from 'react-native'
import {useReactive} from 'ahooks'

interface LinearGradientLineProps extends StyleProp<any> {
  width: number
  height: number
  colors: string[]
  orientation?: 'vertical' | 'horizontal'
}

const LinearGradientLine = (props: LinearGradientLineProps) => {
  const {width, height} = props

  const state = useReactive({
    x1: '0%',
    y1: '50%',
    x2: '100%',
    y2: '50%',
    stops: {},
  })

  useEffect(() => {
    if (props.orientation === 'vertical') {
      state.x1 = '50%'
      state.y1 = '0%'
      state.x2 = '50%'
      state.y2 = '100%'
    } else {
      state.x1 = '0%'
      state.y1 = '50%'
      state.x2 = '100%'
      state.y2 = '50%'
    }
  }, [props.orientation])

  useEffect(() => {
    const p = (1 / (props.colors.length - 1)) * 100
    let pc = 0
    props.colors.forEach(color => {
      state.stops[`${pc}%`] = color
      pc += p
    })
  }, [props.colors])

  return (
    <View style={[{ width, height, overflow: 'hidden' }, props.style]}>
      {JSON.stringify(state.stops) !== '{}' && <LinearGradient
        gradientId="Gradient"
        style={{ width, height }}
        x1={state.x1}
        y1={state.y1}
        x2={state.x2}
        y2={state.y2}
        stops={state.stops}>
        <Rect width={width} height={height} />
      </LinearGradient>}
    </View>
  )
}

export default LinearGradientLine