import { CoverImage, View } from '@tarojs/components'
import Taro, { useDidShow, useRouter } from '@tarojs/taro'
import type { FC } from 'react'
import { useMemo, useState } from 'react'
import classname from 'classnames'
import { useDispatch } from 'react-redux'
import type { Dispatch } from 'redux'
import styles from './index.module.scss'
import IconFont from '@/components/iconfont/iconfont'
import { useSelector } from '@/reducers/hooks'
import { TabBarType } from '@/constants/tabbar'
import type { TabBarAction } from '@/reducers/tabBar'

type IconfontName = Parameters<typeof IconFont>['0']['name']

type TabBarIndexMap = Record<number, {
  id: number
  pagePath: string
  text: string
  iconPath: IconfontName
  selectedIconPath: IconfontName
}>

const CustomTabBar: FC = () => {
  const { selectedId, tabItem } = useSelector((state) => {
    return state.tabBarData
  })
  // const tabBarIndexMap = useMemo(() => {
  //   let map: TabBarIndexMap = {}
  //   for (let i = 0; i < tabItem.length; i++) {
  //     map[tabItem[i].id] = tabItem[i]
  //   }
  //   return map
  // }, [tabItem])
  console.log('selectedId', selectedId)

  const dispatch = useDispatch<Dispatch<TabBarAction>>()
  const setSelected = (id: TabBarIndexMap[number]['id']) => {
    dispatch({ type: TabBarType.SET_SELECTED, data: { tabItem, selectedId: id } })
  }
  const handleSelectTabItem = (id: TabBarIndexMap[number]['id']) => {
    return () => {
      setSelected(id)
      Taro.switchTab({ url: tabItem?.find(item => item.id === id)?.pagePath as string })
    }
  }

  return (
    <View className={styles.customTabBar}>
      <View className={styles['customTabBar-line']}></View>
      {tabItem?.map((item, index) => {
        return (
          <View
            key={index}
            className={classname(styles['customTabBar-item'], styles['customTabBar-item-title'], selectedId === item.id ? styles.selected : '')}
            onClick={handleSelectTabItem(item.id)}
          >
            <IconFont name={Number(selectedId) === item.id ? item.selectedIconPath : item.iconPath} size={56} />

            <View>{item.text}</View>
          </View>
        )
      })}
    </View>
  )
}
export default CustomTabBar
