import React, { useEffect, useState } from 'react';
import { Text, View, ScrollView } from '@tarojs/components';
import classNames from 'classnames';
import connect from '../connect';
import { CompDefault, MetaProps } from '../data-channel';
import fetchMock from '../../common/fetch-mock';

export interface Props extends MetaProps {
  // 数据url
  url: string;
  // 数据输出通道
  onChange: Function;
}

export interface State {
  // 当前项id
  current: string | number;
  // tabs列表
  items: any[];
}

const defaultValue: CompDefault<Props, State> = {
  props: {
    url: '/xxx-list',
    onChange: (_value) => {},
  },
  state: {
    current: 0,
    items: [],
  },
  meta: {
    inners: [{ key: 'items', keyMap: { id: 'id', name: 'title' } }],
  },
};

/**
 * 滚动tabs
 */
const TabsScroll: React.FC<Props> = ({ url, onChange, meta }) => {
  const [current, setCurrent] = useState(defaultValue.state.current);
  const [items, setItems] = useState(defaultValue.state.items);

  useEffect(() => {
    (async () => {
      const dataList = await fetchMock.fetchList('', {});
      setItems(dataList);
    })();
  }, [url]);

  return (
    <View className='wm-tpl-tabs'>
      <ScrollView scrollX>
        <View className='container default'>
          {items.map((item) => {
            const keyMap = meta.inners[0].keyMap;
            const id = item[keyMap.id];
            const active = current === id;
            return (
              <View
                key={id}
                className={classNames('tab', active && 'active')}
                onClick={() => {
                  setCurrent(id);
                  onChange({
                    value: id,
                    meta: meta?.output,
                  });
                }}>
                <Text className='text'>{item[keyMap.name]}</Text>
                {active && <View className='line'></View>}
              </View>
            );
          })}
        </View>
      </ScrollView>
    </View>
  );
};

export default connect(TabsScroll, defaultValue);
