import React, {ReactNode} from 'react'
import {StyleSheet, Text, TouchableOpacity, View, ViewStyle} from 'react-native'
import {Utils} from 'tuya-panel-kit'
import ThemeType from '../config/themeType'

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

interface SegmentedItem {
  label: ReactNode
  value: string | number
}

interface SegmentedProps {
  theme?: ThemeType
  value?: string | number
  options?: SegmentedItem[]
  onChange?: (v: string | number) => void
  style?: ViewStyle
}

const Segmented = (props: SegmentedProps) => {
  const styles = StyleSheet.create({
    wrap_container: {
      flexDirection: 'row',
      height: cx(42),
      backgroundColor: props.theme?.segment.background,
      padding: cx(2),
      borderRadius: cx(8),
    },
    segmented_item: {
      flex: 1,
      alignItems: 'center',
      justifyContent: 'center',
      backgroundColor: props.theme?.container.background,
    },
    segmented_item_first: {
      borderBottomLeftRadius: cx(8),
      borderTopLeftRadius: cx(8),
    },
    segmented_item_last: {
      borderBottomRightRadius: cx(8),
      borderTopRightRadius: cx(8),
    },
    segmented_item_check: {
      backgroundColor: props.theme?.button.primary,
    },
    segmented_text: {
      fontSize: cx(16),
      color: props.theme?.global.secondFontColor,
    },
    segmented_text_check: {
      color: props.theme?.button.fontColor,
    },
  })
  return (
    <View style={[styles.wrap_container, props.style]}>
      {props.options && props.options.map((item, idx) => (
        <TouchableOpacity
          style={[
            styles.segmented_item,
            idx === 0 && styles.segmented_item_first,
            idx + 1 === props.options?.length && styles.segmented_item_last,
            item.value === props.value && styles.segmented_item_check,
          ]}
          onPress={() => props.onChange && props.onChange(item.value)}
          key={idx}
        >
          <Text style={[
            styles.segmented_text,
            item.value === props.value && styles.segmented_text_check,
          ]}>{item.label}</Text>
        </TouchableOpacity>
      ))}
    </View>
  )
}

export default withTheme(Segmented) as React.ComponentType<SegmentedProps>
