import React, { useState } from 'react';
import { View } from '@tarojs/components';
import { bindOnChange, bindStateToProp, CompDefault, MetaProps } from '../data-channel';
import connect from '../connect';

export interface Props extends MetaProps {
  // 子tab列表
  children: JSX.Element[];
  // 数据输出通道
  onChange: Function;
}

export interface State {
  // 当前激活的tab
  activeTab: number;
}

/**
 * 默认值
 */
const defaultValue: CompDefault<Props, State> = {
  props: {
    children: [],
    onChange: (_value) => {},
  },
  state: {
    activeTab: 0,
  },
  meta: {
    compName: 'tabsHub:tabs集合',
    inputs: [{ key: 'children', type: 'array', tags: ['jsx'] }],
  },
};

/**
 * tabsHub
 */
const TabsHub: React.FC<Props> = ({ children, onChange }) => {
  const [activeTab, setActiveTab] = useState(defaultValue.state.activeTab);

  children = children.map((item, idx) => {
    bindOnChange(item, ({ value, meta }) => {
      if (meta.tags.includes('check-tab')) {
        setActiveTab(idx);
      }
      if (meta.tags.includes('search-item')) {
        onChange({ value, meta });
      }
    });
    bindStateToProp(item, 'active', () => activeTab == idx);
    return item;
  });

  return <View className='wm-tabs-hub'>{children}</View>;
};

export default connect(TabsHub, defaultValue);
