import React, { useState, useCallback } from 'react';
import { View, ScrollView } from '@tarojs/components';
import CategoryTabbarMore from '../CategoryTabbarMore';
import './CategoryTabbar.css';

interface TabItem {
  id: string;
  name: string;
  disabled?: boolean;
}

interface CategoryTabbarProps {
  tabList: TabItem[];
  currentActive?: string;
  showMore?: boolean;
  onChange?: (id: string) => void;
  className?: string;
}

const CategoryTabbar: React.FC<CategoryTabbarProps> = ({
  tabList,
  currentActive,
  showMore = true,
  onChange,
  className = '',
}) => {
  const [activeId, setActiveId] = useState<string | undefined>(currentActive);

  const handleItemClick = useCallback((id: string) => {
    setActiveId(id);
    onChange?.(id);
  }, [onChange]);

  const shouldShowMore = showMore && tabList.length > 4;

  return (
    <View className={`c-tabbar ${className}`}>
      {tabList.length > 0 && (
        <ScrollView
          className="c-tabbar__scroll"
          scrollX
          scrollIntoView={activeId ? `id-${activeId}` : undefined}
        >
          <View className={`c-tabbar__inner ${shouldShowMore ? 'c-tabbar__inner_more' : ''}`}>
            {tabList.map((item) => (
              <View
                key={item.id}
                id={`id-${item.id}`}
                className={`c-tabbar-item ${activeId === item.id ? 'active' : ''} ${item.disabled ? 'disabled' : ''}`}
                onClick={() => !item.disabled && handleItemClick(item.id)}
              >
                <View className="c-tabbar-item__text">{item.name}</View>
              </View>
            ))}
          </View>
        </ScrollView>
      )}
      {shouldShowMore && (
        <CategoryTabbarMore
          tabList={tabList}
          onSelect={handleItemClick}
        />
      )}
    </View>
  );
};

export type { CategoryTabbarProps, TabItem };
export default CategoryTabbar;