import { exchangeNumber, localeNumber } from "../utils/common";
import res from "@res";
import { useReactive } from "ahooks";
import React, { memo, useCallback } from "react";
import { TouchableOpacity, View, Image, TextInput, StyleSheet, StyleProp, ViewStyle } from "react-native";
import { Utils } from "tuya-panel-kit";
import ThemeType from '../config/themeType'

const { add, subtract, inMaxMin } = Utils.NumberUtils

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

export interface StepperProps {
  theme?: ThemeType
  value: number | string
  stepValue?: number  // 1
  min?: number  // 0
  max?: number // 99
  editable?: boolean
  selectionColor?: string
  isRealTime?: boolean
  isBeyond?: boolean // 允许超出边界值
  onValueChange?: ((value: number) => void)
  disabled?: boolean
  style?: StyleProp<ViewStyle>
  buttonStyle?: StyleProp<ViewStyle>
  inputStyle?: StyleProp<ViewStyle>
}

const Stepper = (props: StepperProps) => {
  const state = useReactive({
    value: localeNumber(Number(props.value), 1) ?? 0,
    stepValue: props.stepValue ?? 1,
    min: props.min ?? 0,
    max: props.max ?? 99
  })

  const handlePress = useCallback((isAdd: boolean) => {
    const v = inMaxMin(state.min, state.max, isAdd ? add(Number(exchangeNumber(state.value)), state.stepValue) : subtract(Number(exchangeNumber(state.value)), state.stepValue))
    state.value = localeNumber(v, 1)
    props.onValueChange && props.onValueChange(v)
  }, [])


  const handleChangeText = useCallback((v: string) => {
    const newValue = exchangeNumber(v)
    const idx = newValue.indexOf('.')
    if (newValue[0] === '.' ||
      (newValue.length === 2 && newValue[0] === '0' && newValue[1] !== '.') ||
      newValue.split('').filter(item => item === '.').length > 1 ||
      (!props.isBeyond && (Number(newValue) > state.max || Number(newValue) < state.min)) ||
      (idx !== -1 && newValue.length > idx + 2)) {
      return
    }
    if (props.isRealTime) {
      if (typeof v === 'string' && !v.length) {
        props.onValueChange && props.onValueChange(0)
      } else {
        props.onValueChange && props.onValueChange(Number(exchangeNumber(v)))
      }
    }
    state.value = v
  }, [])

  const handleEndText = useCallback(() => {
    if (typeof state.value === 'string' && !state.value.length) {
      props.onValueChange && props.onValueChange(state.min)
      state.value = state.min.toString()
    } else {
      props.onValueChange && props.onValueChange(Number(exchangeNumber(state.value)))
    }

  }, [])


  const styles = StyleSheet.create({
    stepperContainer: {
      flexDirection: 'row',
      alignItems: 'center',
      backgroundColor: props.theme?.container.background,
      padding: cx(2),
      borderRadius: cx(12),
      width: cx(150),
    },
    stepperButton: {
      width: cx(52),
      height: cx(28),
      backgroundColor: props.theme?.global.background,
      borderRadius: cx(10),
      alignItems: 'center',
      justifyContent: 'center',
    },
    stepperIcon: {
      width: cx(20),
      height: cx(20),
      tintColor: props.theme?.global.fontColor
    },
    stepperInput: {
      width: cx(42),
      height: cx(22),
      color: props.theme?.global.secondFontColor,
      fontSize: cx(16),
      padding: 0,
      alignItems: 'center',
      justifyContent: 'center',
      textAlign: 'center',
    }
  })

  return (
    <View style={[styles.stepperContainer, props.style]}>
      <TouchableOpacity
        style={[styles.stepperButton, props.buttonStyle]}
        onPress={() => handlePress(false)}
      >
        <Image style={styles.stepperIcon} source={res.ic_minus} />
      </TouchableOpacity>
      <TextInput
        style={[styles.stepperInput, props.inputStyle]}
        value={state.value.toString()}
        keyboardType="numeric"
        onChangeText={handleChangeText}
        maxLength={4}
        enablesReturnKeyAutomatically={true}
        onEndEditing={handleEndText}
        editable={props.editable || props.disabled}
      />
      <TouchableOpacity
        style={[styles.stepperButton, props.buttonStyle]}
        onPress={() => handlePress(true)}
      >
        <Image style={styles.stepperIcon} source={res.ic_plus} />
      </TouchableOpacity>
    </View>
  )
}

export default memo(withTheme(Stepper))
