import React, { useCallback } from 'react'
import { FlatList, StyleSheet, View, Image } from 'react-native'
import AdvanceCard, { AdvancedData } from './AdvanceCard'
import Spacer from './Spacer'
import { useNavigation } from '@react-navigation/core'
import { Utils } from 'tuya-panel-kit'
import { getMicrophoneAccess } from '../api/native'

const { convertX: cx } = Utils.RatioUtils

const MusicRouterKey = ['ui_biz_music', 'group_ui_biz_music']

export interface AdvanceListProps {
  advanceData: AdvancedData[],
  onAdvanceItemClick?: (advanceData: AdvancedData, index: number) => void | undefined
}

function AdvanceList(props: AdvanceListProps) {
  const navigation = useNavigation()

  const { advanceData, onAdvanceItemClick } = props

  const renderItem = useCallback(({ item, index }) => (
    <View style={styles.item}>
      <AdvanceCard
        data={item}
        onPress={async () => {
          if(MusicRouterKey.includes(item.router.key)){
            getMicrophoneAccess().then(res =>{
              if(!res) return
              navigation.navigate(item.router.key, item.router.params)
            })
          }else{
            if (!onAdvanceItemClick || onAdvanceItemClick(item, index)) {
              navigation.navigate(item.router.key, item.router.params)
            }
          }
        }}>
        {item.icons && <View style={{
          height: cx(118),
          justifyContent: 'center',
          alignItems: 'center',
        }}>
          <Image source={item.icons} style={{ width: cx(80), height: cx(80) }} />
        </View>}
      </AdvanceCard>
    </View>
  ), [navigation, onAdvanceItemClick])

  const keyExtractor = useCallback((item: AdvancedData, index: number) => item.dp?.code || `key-${index}`, [])

  const Header = useCallback(() => <Spacer height={cx(10)} />, [])
  const Separator = useCallback(() => <Spacer />, [])
  const Footer = useCallback(() => <Spacer height={cx(30)} />, [])

  return (
    <FlatList
      numColumns={2}
      style={styles.container}
      data={advanceData}
      renderItem={renderItem}
      keyExtractor={keyExtractor}
      ListHeaderComponent={Header}
      ItemSeparatorComponent={Separator}
      ListFooterComponent={Footer} />
  )
}

const styles = StyleSheet.create({
  container: {
    marginHorizontal: cx(14),
  },
  item: {
    flex: .5,
    justifyContent: 'center',
    alignItems: 'center',
  },
})

export default React.memo(AdvanceList)
