import { DeviceInfo } from '../api/native'
import React from 'react'
import ApplyForText from './ApplyForText'
import { FlatList, StyleSheet, View } from 'react-native'
import Spacer from './Spacer'
import ApplyForDeviceItem from './ApplyForDeviceItem'
import { Utils } from 'tuya-panel-kit'
import { useReactive, useUpdateEffect } from 'ahooks'
import ThemeType from '../config/themeType'

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

export interface ApplyForDeviceListProps {
  theme?: ThemeType
  devices: DeviceInfo[]
  expand?: boolean
  onExpandChange?: (expand: boolean) => void
}

const ApplyForDeviceList = (props: ApplyForDeviceListProps) => {
  const state = useReactive({
    expand: props.expand || false
  })

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

  const styles = StyleSheet.create({
    deviceList: {
      marginHorizontal: cx(16),
      paddingVertical: cx(8),
      backgroundColor: props.theme?.container.background,
    },
    spacer: {
      backgroundColor: props.theme?.container.background,
    }
  })

  return <View>
    <ApplyForText
      expand={state.expand}
      onExpandChange={(expand) =>{
        if(props.onExpandChange){
          props.onExpandChange(expand)
        }else{
          state.expand = expand
        }
      }}/>
    <Spacer height={cx(2)}/>
    {state.expand &&
        <FlatList
            style={styles.deviceList}
            data={props.devices}
            renderItem={({ item }) => <ApplyForDeviceItem deviceInfo={item}/>}
            keyExtractor={item => item.deviceId}
            ItemSeparatorComponent={() => {
              return (
                <Spacer
                  style={styles.spacer}
                  height={cx(8)}/>
              )
            }}/>}
  </View>
}

export default withTheme(ApplyForDeviceList)
