import React, { useMemo } from 'react'
import { View, StyleSheet } from 'palife-lib-fluid/base-components'
import Svg, { LinearGradient as SvgLinearGradient, Stop, Defs, Rect } from 'react-native-svg'
import { LinearGradientProps } from './types'
import { createIDString } from 'palife-lib-key-ui/utils/createIDString'
export const LinearGradient = ({
style = {},
start = {
x: 0.5,
y: 0,
},
end = {
x: 0.5,
y: 1,
},
locations = [],
colors = [],
width = 1,
height = 1,
radius = 0,
children,
native_opacityLocations,
...restProps
}: LinearGradientProps) => {
const id = useMemo(() => createIDString(), [])
const getLocationConfig = () => {
return {
x1: width * Number(start.x),
y1: height * Number(start.y),
x2: width * Number(end.x),
y2: height * Number(end.y),
}
}
const getStopComponents = () => {
return colors.map((color, index) => {
const location = locations[index]
const opacityLocation = native_opacityLocations[index]
return <Stop stopOpacity={opacityLocation} offset={location} stopColor={color} />
})
}
return (
<View style={StyleSheet.merge(style, { width, height })} {...restProps}>
<Svg style={{ position: 'absolute' }} width={width} height={height}>
<Defs>
<SvgLinearGradient id={id} {...getLocationConfig()}>
{getStopComponents()}
</SvgLinearGradient>
</Defs>
<Rect width={width} height={height} rx={radius} ry={radius} fill={`url(#${id})`} />
</Svg>
{children}
</View>
)
}