import {useReactive} from 'ahooks'
import React, {useEffect} from 'react'
import {StyleProp, StyleSheet, Text, TextStyle, View, ViewStyle} from 'react-native'
import {Slider, Utils} from 'tuya-panel-kit'
import ThemeType from '../config/themeType'

const cx = Utils.RatioUtils.convertX
const { withTheme } = Utils.ThemeUtils

interface LdvSliderProps {
  theme?: ThemeType
  title: string,
  value: number,
  min?: number | undefined,
  max?: number | undefined,
  onValueChange?: (v: number) => void | undefined,
  onSlidingComplete: (v: number) => void,
  style?: StyleProp<ViewStyle> | undefined,
  sliderStyle?: StyleProp<ViewStyle> | undefined
  subTitleStr?: string | number
  titleStyle?: StyleProp<TextStyle> | undefined
}

const LdvSlider = (props: LdvSliderProps) => {
  const {value, onSlidingComplete, min, max, sliderStyle, subTitleStr, titleStyle, onValueChange} = props

  const mMax = max || 100
  const mMin = min ?? 1
  const state = useReactive({
    value: value,
  })
  useEffect(() => {
    state.value = value
  }, [value])

  const styles = StyleSheet.create({
    container: {
      flexDirection: 'column',
      paddingHorizontal: cx(16),
    },
    titleBg: {
      flexDirection: 'row',
      justifyContent: 'space-between',
    },
    valueText: {
      marginTop: cx(10),
      fontSize: cx(14),
      color: props.theme?.global.fontColor,
      fontFamily: 'helvetica_neue_lt_std_roman',
    },
    title: {
      marginTop: cx(10),
      fontSize: cx(14),
      color: props.theme?.global.fontColor,
      fontFamily: 'helvetica_neue_lt_std_roman',
    },
    slider: {
      marginTop: cx(8),
      height: cx(28),
      justifyContent: 'center',
    },
    thumb: {
      backgroundColor: '#fff',
      width: cx(28),
      height: cx(28),
      borderRadius: cx(14),
      shadowColor: '#000000',
      shadowOpacity: 0.2,
      elevation: cx(8),
      shadowRadius: cx(8),
      shadowOffset: {
        width: 0,
        height: cx(4),
      },
    },
  })

  return (
    <View style={[styles.container, props.style]}>
      <View style={styles.titleBg}>
        <Text style={[styles.title, titleStyle]}>
          {props.title}
        </Text>
        <Text style={styles.valueText}>
          {subTitleStr ? subTitleStr : state.value + '%'}
        </Text>
      </View>
      <Slider.Horizontal
        style={[styles.slider, sliderStyle]}
        styles={{thumb: styles.thumb}}
        maximumValue={mMax}
        minimumValue={mMin}
        value={state.value}
        stepValue={1}
        canTouchTrack={true}
        minimumTrackTintColor={'#666'}
        maximumTrackTintColor={'rgba(120, 120, 128, 0.2)'}
        onValueChange={(value) => {
          state.value = value
          onValueChange && onValueChange(value)
        }}
        onSlidingComplete={onSlidingComplete}
      />
    </View>
  )
}

export default withTheme(LdvSlider)
