import { ScrollView, View } from '@tarojs/components'
import classnames from 'classnames'
import type { FC } from 'react'
import { useEffect, useState } from 'react'
import styles from './index.module.scss'

interface Segment {
  id: number
  name: string
}

interface PropsType {
  list: Segment[]
  defaultId?: number
  onSelect?: (data: { id: number; name: string }) => void
}

const segmentedControl: FC<PropsType> = (props) => {
  const [selectInfo, setSelectInfo] = useState({
    selected: -1, // 当前选中的id
    tabId: '', // 需要滚动到的id
  })
  const { list, defaultId = -1, onSelect } = props

  const isValidNumber = (value: any) => {
    return typeof value === 'number' && value >= 0
  }

  useEffect(() => {
    console.log('defaultId', defaultId)
    if (isValidNumber(defaultId)) {
      console.log('defaultId:::', defaultId)
      const index = list?.findIndex((item) => {
        return item.id == defaultId
      })
      if (index !== -1) {
        const num = index > 0 ? index - 1 : 0
        setSelectInfo(e => ({ ...e, tabId: list[num].id.toString() }))
      }
    }
    setSelectInfo(e => ({ ...e, selected: isValidNumber(defaultId) ? defaultId : -1 }))
    console.log('selectInfo', selectInfo)
  }, [defaultId])

  const clickEvent = ({ item, index }: { item: any; index: number }) => {
    const num = index > 0 ? index - 1 : 0
    setSelectInfo(e => ({ ...e, tabId: list[num].id.toString(), selected: item.id }))
    onSelect?.(item)
  }

  return (
    <View className={styles.status_list}>
      <ScrollView scrollX scrollIntoView={`tabs_${selectInfo.tabId}`} scrollWithAnimation>
        <View className={styles.list_scroll}>
          {list.map((item, index) => {
            return (
              <View
                key={item.id}
                id={`tabs_${item.id}`}
                onClick={() => clickEvent({ item, index })}
                className={classnames(styles.status_item, selectInfo.selected === item.id ? styles.selected : '')}
              >
                {item.name}
              </View>
            )
          })}
        </View>
      </ScrollView>
    </View>
  )
}
export default segmentedControl
