import React, { PropsWithChildren, ReactChild, useCallback, useEffect, useMemo } from 'react'
import { Image, StyleSheet, Text, TouchableOpacity, View, ViewProps } from 'react-native'
import { Modal, Utils } from 'tuya-panel-kit'
import { useReactive, useUpdateEffect } from 'ahooks'
import Card from './Card'
import res from '@res'
import I18n from '@i18n'
import LdvSwitch from './ldvSwitch'
import LampAdjustView from './LampAdjustView'
import { hsv2Hex, mapFloatToRange } from '@utils'
import Spacer from './Spacer'
import DeleteButton from './DeleteButton'
import Stepper from './Stepper'
import StripLightView from './StripLightView'
import { nativeEventEmitter } from '../api/nativeEventEmitter'
import ThemeType from '../config/themeType'

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

export type Node = {
  color: string,
  backgroundColor?: string
}

interface DrawToolViewProps extends PropsWithChildren<ViewProps> {
  theme?: ThemeType
  title?: string
  switchLed?: boolean
  showEnable?: boolean
  setEnable: (enable: boolean) => void
  adjustType?: 1 | 2 | 3   // 1 全选, 2 单选, 3 擦除
  setAdjustType: (type: number) => void
  stripStyle?: 'ONLY_LINE' | 'WITH_BEAD'
  nodes: Node[]
  fixCount?: number
  touchingMode?: 'CLICK' | 'TOUCH'
  nodeTouch: (idx: number) => void
  fingerUp: (idxList: string) => void
  hideLightView?: boolean
  isSupportColor?: boolean
  isSupportTemperature?: boolean
  isSupportBrightness?: boolean
  isColorMode?: boolean
  setIsColorMode: (isColorMode: boolean) => void
  blockColor?: string
  h: number
  s: number
  v: number
  onHSVChange: (h: number, s: number, v: number) => void
  onHSVChangeComplete: (h: number, s: number, v: number) => void
  temperature: number
  brightness: number
  onCCTChange: (cct: number) => void
  onCCTChangeComplete: (cct: number) => void
  onBrightnessChange: (brightness: number) => void
  onBrightnessChangeComplete: (brightness: number) => void
  hideLedNum?: boolean
  ledNum?: number
  setLedNum: (num: number) => void
  hidLampAdjustView?: boolean
  hideDisableLight?: boolean
  hideColorize?: boolean
  ledNumModalVisible?: boolean
  deviceGroupContent?: ReactChild
}

const DrawToolView = (props: DrawToolViewProps) => {
  const state = useReactive({
    visible: props.ledNumModalVisible || false,
    ledNum: props.ledNum || 5,
    width: 0,
  })

  useEffect(() => {
    const fingerUp = nativeEventEmitter.addListener('onFingerUp', props.fingerUp)

    const nodeTouched = nativeEventEmitter.addListener('onNodeTouched', props.nodeTouch)
    return () => {
      fingerUp.remove()
      nodeTouched.remove()
    }
  }, [])

  useUpdateEffect(() =>{
    if(props.ledNum){
      state.ledNum = props.ledNum
    }
  }, [props.ledNum])

  useUpdateEffect(() =>{
    state.visible = props.ledNumModalVisible || false
  }, [props.ledNumModalVisible])

  const onLayout = (event: any) => {
    const { width } = event.nativeEvent.layout
    state.width = width
  }

  const height = useMemo(() => {
    return cx(52 * Math.ceil((props.nodes.length / (props.fixCount || 5))))
  }, [props.nodes])

  const getBlockColor = useCallback(() => {
    if (props.isColorMode) {
      const s = Math.round(mapFloatToRange(props.s / 100, 30, 100))
      return hsv2Hex(props.h, s, 100)
    }
    return props.theme?.card.background
  }, [props.isColorMode, props.h, props.s])

  const ledNumValidator = (num?: number) => {
    return num && Number.isInteger(num) && num >= 5 && num <= 48;
  }


  const styles = StyleSheet.create({
    container: {
      paddingLeft: cx(10),
      flexDirection: 'row',
      alignItems: 'center',
    },
    title: {
      color: props.theme?.global.fontColor,
      fontSize: cx(16),
      marginLeft: cx(10),
      fontFamily: 'helvetica_neue_lt_std_bd',
      fontWeight: 'bold',
    },
    adjustButtons: {
      width: cx(50),
    },
    adjustButton: {
      width: cx(44),
      height: cx(44),
    },
  })

  return (
    <Card style={{ marginHorizontal: cx(24) }}>
      <LdvSwitch
        title={props.title || I18n.getLang('light_sources_tile_tw_lighting_headline')}
        color={props.theme?.card.background}
        colorAlpha={1}
        enable={!!props.switchLed}
        showSwitch={!!props.showEnable}
        setEnable={props.setEnable} />
      {(props.showEnable && props.switchLed || !props.showEnable) && <>
          <View style={styles.container}>
              <View style={styles.adjustButtons}>
                  <TouchableOpacity
                      onPress={() => {
                        props.setAdjustType(1)
                      }}>
                      <Image
                          style={[styles.adjustButton, { tintColor: props.adjustType === 1 ? props.theme?.icon.primary : props.theme?.icon.normal }]}
                          source={res.ic_paint_bucket} />
                  </TouchableOpacity>
                {!props.hideDisableLight && <TouchableOpacity
                    onPress={() => {
                      props.setAdjustType(3)
                    }}>
                    <Image
                        style={[styles.adjustButton, { tintColor: props.adjustType === 3 ? props.theme?.icon.primary : props.theme?.icon.normal }]}
                        source={res.ic_disabled_light} />
                </TouchableOpacity>}
                {!props.hideColorize && <TouchableOpacity
                    onPress={() => {
                      props.setAdjustType(2)
                    }}>
                    <Image
                        style={[styles.adjustButton, { tintColor: props.adjustType === 2 ? props.theme?.icon.primary : props.theme?.icon.normal }]}
                        source={res.ic_colorize} />
                </TouchableOpacity>}
                {!props.hideLedNum && <TouchableOpacity
                    onPress={() => {
                      state.visible = true
                    }}
                    style={[styles.adjustButton, {
                      alignItems: 'center',
                      justifyContent: 'center',
                      backgroundColor: props.theme?.icon.primary,
                      borderRadius: cx(5),
                    }]}>
                    <Text style={{ color: props.theme?.global.fontColor, fontSize: cx(18), fontWeight: 'bold' }}>{props.ledNum || 5}</Text>
                </TouchableOpacity>}
              </View>
              <StripLightView
                  style={{ height, flex: 1 }}
                  nodes={props.nodes}
                  fixCount={props.fixCount || 5}
                  stripStyle={props.stripStyle || 'WITH_BEAD'}
                  touchingMode={props.touchingMode || 'TOUCH'}
                  width={state.width}
                  onLayout={onLayout} />
          </View>
          <LdvSwitch
              title={I18n.getLang('light_sources_tile_tw_lighting_headline')}
              color={props.blockColor || getBlockColor()}
              colorAlpha={1}
              enable={false}
              showSwitch={false}
              setEnable={() => {
              }} />
        {!props.hidLampAdjustView && <LampAdjustView
            isSupportColor={!!props.isSupportColor}
            isSupportTemperature={!!props.isSupportTemperature}
            isSupportBrightness={!!props.isSupportBrightness}
            isColorMode={!!props.isColorMode}
            reserveSV={true}
            minSaturation={1}
            setIsColorMode={props.setIsColorMode}
            h={props.h} s={props.s} v={props.v}
            onHSVChange={props.onHSVChange}
            onHSVChangeComplete={props.onHSVChangeComplete}
            colorTemp={props.temperature}
            brightness={props.brightness}
            onCCTChange={props.onCCTChange}
            onCCTChangeComplete={props.onCCTChangeComplete}
            onBrightnessChange={props.onBrightnessChange}
            onBrightnessChangeComplete={props.onBrightnessChangeComplete} />}
        {!props.hideLedNum && <Modal
            visible={state.visible}
            onMaskPress={() => {
              state.visible = false
            }}
            alignContainer="center"
            style={{ width: '100%', height: cx(150) }}>
            <Card
                containerStyle={{ marginHorizontal: cx(16), alignItems: 'center' }}
                style={{ marginHorizontal: cx(16), marginTop: cx(50) }}>
                <Spacer />
                <Text style={{ color: props.theme?.global.fontColor, fontSize: cx(14) }}>{I18n.getLang('string_lights_set_bulbs_title')}</Text>
                <Spacer height={cx(10)}/>
                <Text style={{color: props.theme?.global.secondFontColor}}>{I18n.getLang('string_lights_set_bulbs_description_text')}</Text>
                <Spacer />
                <Stepper
                    min={5}
                    max={48}
                    isBeyond={true}
                    stepValue={1}
                    editable={true}
                    value={state.ledNum}
                    isRealTime={true}
                    onValueChange={(v) => {
                      state.ledNum = v
                    }} />
                <Spacer />
                <DeleteButton
                    text={I18n.getLang('auto_scan_system_wifi_confirm')}
                    style={{ width: cx(150), height: cx(40), backgroundColor: ledNumValidator(state.ledNum) ? props.theme?.button.primary : props.theme?.button.disabled }}
                    textStyle={{ fontSize: cx(14) }}
                    onPress={() => {
                      if (!ledNumValidator(state.ledNum)) return
                      props.setLedNum(state.ledNum)
                      state.visible = false
                    }} />
                <Spacer />
            </Card>
        </Modal>}
        {props.children}
      </>}
      {props.deviceGroupContent ? props.deviceGroupContent : undefined}
    </Card>
  )
}


export default withTheme(DrawToolView)
