import React, { useState, useEffect } from 'react'
import { View, ScrollView, Text } from '@tarojs/components'
import TDesignIcon from '../icon'
import './index.css'

interface TabItem {
  label: string
  value?: string
  disabled?: boolean
  icon?: string
  badgeProps?: {
    dot?: boolean
    count?: number
  }
}

interface TabsProps {
  value?: string | number
  defaultValue?: string | number
  list: TabItem[]
  theme?: 'line' | 'card' | 'tag'
  placement?: 'top' | 'left' | 'right' | 'bottom'
  showBottomLine?: boolean
  spaceEvenly?: boolean
  split?: boolean
  swipeable?: boolean
  sticky?: boolean
  onChange?: (value: string | number, index: number) => void
  children?: React.ReactNode
}

export default function TDesignTabs({
  value,
  defaultValue,
  list = [],
  theme = 'line',
  placement = 'top',
  showBottomLine = true,
  spaceEvenly = true,
  split = true,
  onChange,
  children
}: TabsProps) {
  const [currentIndex, setCurrentIndex] = useState(0)

  // 初始化当前选中项
  useEffect(() => {
    if (value !== undefined) {
      const index = list.findIndex(item =>
        item.value !== undefined ? item.value === value : item.label === value
      )
      if (index !== -1) setCurrentIndex(index)
    } else if (defaultValue !== undefined) {
      const index = list.findIndex(item =>
        item.value !== undefined ? item.value === defaultValue : item.label === defaultValue
      )
      if (index !== -1) setCurrentIndex(index)
    }
  }, [value, defaultValue, list])

  const handleTabClick = (index: number, item: TabItem) => {
    if (item.disabled) return

    setCurrentIndex(index)
    const selectedValue = item.value !== undefined ? item.value : item.label
    onChange?.(selectedValue, index)
  }

  const getActiveColor = () => {
    return theme === 'line' ? 'var(--td-tab-item-active-color, #fa550f)' : 'var(--td-tab-item-active-color, #fa550f)'
  }

  const getInactiveColor = () => {
    return theme === 'line' ? 'var(--td-tab-item-color, #333)' : '#666'
  }

  return (
    <View className={`tdesign-tabs tdesign-tabs--${placement}`}>
      {/* 标签栏 */}
      <View className={`tdesign-tabs__wrapper tdesign-tabs__wrapper--${theme}`}>
        <ScrollView
          className={`tdesign-tabs__scroll ${split ? 'tdesign-tabs__scroll--split' : ''}`}
          scrollX={true}
          scrollWithAnimation={true}
          showScrollbar={false}
          enhanced
          enableFlex
        >
          <View
            className={`tdesign-tabs__nav ${spaceEvenly ? 'tdesign-tabs__nav--evenly' : ''}`}
            aria-role="tablist"
          >
            {list.map((item, index) => (
              <View
                key={index}
                className={`
                  tdesign-tabs__item
                  tdesign-tabs__item--${theme}
                  ${spaceEvenly ? 'tdesign-tabs__item--evenly' : ''}
                  ${currentIndex === index ? 'tdesign-tabs__item--active' : ''}
                  ${item.disabled ? 'tdesign-tabs__item--disabled' : ''}
                `}
                onClick={() => handleTabClick(index, item)}
                aria-role="tab"
                aria-selected={currentIndex === index}
                aria-disabled={item.disabled}
                aria-label={item.label}
              >
                <View
                  className={`
                    tdesign-tabs__item-inner
                    tdesign-tabs__item-inner--${theme}
                    ${currentIndex === index ? 'tdesign-tabs__item-inner--active' : ''}
                  `}
                >
                  {item.icon && (
                    <TDesignIcon
                      name={item.icon}
                      size="var(--td-tab-icon-size, 36rpx)"
                      color={currentIndex === index ? getActiveColor() : getInactiveColor()}
                      className="tdesign-tabs__icon"
                    />
                  )}

                  {item.badgeProps ? (
                    <View className="tdesign-tabs__badge">
                      <Text>{item.label}</Text>
                      {item.badgeProps.dot && (
                        <View className="tdesign-tabs__badge-dot" />
                      )}
                      {item.badgeProps.count && item.badgeProps.count > 0 && (
                        <View className="tdesign-tabs__badge-count">
                          <Text>{item.badgeProps.count}</Text>
                        </View>
                      )}
                    </View>
                  ) : (
                    <Text
                      style={{
                        color: currentIndex === index ? getActiveColor() : getInactiveColor(),
                        fontWeight: currentIndex === index ? '600' : '400'
                      }}
                    >
                      {item.label}
                    </Text>
                  )}
                </View>

                {/* 卡片主题的特殊样式 */}
                {theme === 'card' && currentIndex - 1 === index && (
                  <View className="tdesign-tabs__item-prefix" />
                )}
                {theme === 'card' && currentIndex + 1 === index && (
                  <View className="tdesign-tabs__item-suffix" />
                )}
              </View>
            ))}

            {/* 底部指示线 */}
            {showBottomLine && theme === 'line' && (
              <View
                className="tdesign-tabs__track"
                style={{
                  backgroundColor: 'var(--td-tab-track-color, #fa550f)',
                  width: 'var(--td-tab-track-width, 32rpx)',
                  height: 'var(--td-tab-track-thickness, 6rpx)',
                  borderRadius: 'var(--td-tab-track-radius, 8rpx)',
                  transform: `translateX(${currentIndex * 100}%)`,
                  transition: 'transform 0.3s ease'
                }}
              />
            )}
          </View>
        </ScrollView>
      </View>

      {/* 内容区域 */}
      <View className="tdesign-tabs__content">
        <View className="tdesign-tabs__content-inner">
          {children && React.Children.map(children, (child, index) => (
            <View
              key={index}
              style={{
                display: currentIndex === index ? 'block' : 'none'
              }}
            >
              {child}
            </View>
          ))}
        </View>
      </View>
    </View>
  )
}