import React from 'react';
import { formatMessage } from 'umi-plugin-locale';

import styles from './style.less';

export interface TabItemModel {
  key: string;
  name: string;
  icon?: string;
  iconSelected?: string;
}

export type TabItemModels = TabItemModel[];

export interface TabProps {
  items: TabItemModels;
  selectedKey?: string;
  onChange?: (key: string) => void;
}

const Tab: React.FC<TabProps> = ({
  items,
  selectedKey,
  onChange,
}) => {
  const onItemClick = (key: string) => {
    if (onChange) {
      onChange(key);
    }
  };

  const itemWidth = { width: `${100 / (items.length || 1)}%` };
  return (
    <div className={styles.tab}>
      {items.map(item => (
        <div
          onClick={() => onItemClick(item.key)}
          style={itemWidth}
          className={`${styles.item} ${item.key === selectedKey ? styles.active : ''}`}
          key={item.key}
        >
          {item.icon && item.iconSelected && <img src={item.key === selectedKey ? item.iconSelected : item.icon} />}
          <span>{formatMessage({ id: item.name })}</span>
        </div>
      ))}
    </div>
  )
};

export default Tab;
