import {CSSProperties, FC, useEffect, useState} from "react";
import './tabs.scss'
import {ScrollView, View} from "@tarojs/components";
import Taro from "@tarojs/taro";


export interface TabList<T = unknown> {
  title: string
  value?: number | string | Record<string, T> | T

  [key: string]: any
}

export type OnChangOpt<T = unknown> = {
  index: number,
  tab?: { title: string, value?: number | string | Record<string, T> | T }
}

interface TabsProps {
  current?: number | string
  tabList: TabList[]
  height?: number | string
  onChange?: (data: OnChangOpt) => void
  backMode?: boolean // 块级模式
  style?: CSSProperties
}

const Tabs: FC<TabsProps> = (opt) => {
  const {screenWidth} = Taro.getApp().globalData
  const [current, setCurrent] = useState<number | string>(opt.current || 0)
  const [left, setLeft] = useState(0)

  useEffect(() => {
    setCurrent(opt.current || 0)
  }, [opt.current])

  function onChange(event: any, index: number, tab: TabList) {
    const offsetLeft = event.target.offsetLeft
    setLeft(offsetLeft - screenWidth / 2)
    setCurrent(index)
    opt?.onChange?.({index, tab})
  }

  function is_current(value: unknown, index: number): boolean {
    if (opt.current) {
      return String(value) === String(opt.current)
    }
    return index === current
  }


  return (
    <View className={`tabs ${opt.backMode ? 'tabsBack' : ''}`} style={{height: opt.height, ...opt.style}}>
      <ScrollView scrollX scrollLeft={left} scrollWithAnimation showScrollbar={false} style={{height: opt.height}}>
        <View className={'tabs-scroll ' + (opt.tabList.length < 5 ? 'justify-around' : '')}>
          {opt.tabList.map((d, index) => <View
            key={index}
            className={'tabs-item ' + (is_current(d.value, index) ? 'current' : null)}
            onClick={(event) => onChange(event, index, d)}>
            {d.title}
          </View>)}
        </View>
      </ScrollView>
    </View>
  )
}

export default Tabs
