import React, { useState } from 'react';

import {
  TipsIconStyle,
  IndicatorCardTitleStyle,
  IndicatorCardMainStyle,
  IndicatorCardStyle,
  IndicatorFlexStyle,
  IndicatorIcon,
  IndicatorCardBoxStyle,
} from './styles';
import { ICustomValue, IIndicatorData, YIndicatorCardProps } from './indicatorCard.interface';
import { YPopover } from '../../popover';

export const YIndicatorCard: React.FC<YIndicatorCardProps> = (
  {
    dataSource,
    style,
    icon,
    tipsWidth = 200,
    onClick,
    ableClick,
  },
) => {
  const [cardSelect, setCardSelect] = useState<number>(-1);

  const handleChick = (item: IIndicatorData, index: number) => {
    if (!ableClick) return;
    if (cardSelect === index) {
      setCardSelect(-1);
    } else {
      setCardSelect(index);
    }
    onClick && onClick(item, index);
  };

  const renderIndicatorCard = (item: IIndicatorData, index: number) => {
    return (
      <IndicatorCardStyle
        key={`card-${index}`}
        style={style}
        onClick={() => handleChick(item, index)}
        role={cardSelect === index ? 'yes' : 'no'}
      >
        {
          Object.keys(item).map((keys: string) => {
            let data: ICustomValue = item[keys];
            return <IndicatorFlexStyle>
              <YPopover content={data.remark} originProps={{ placement: 'bottomLeft' }} style={{ width: tipsWidth }}>
                {
                  icon
                    ? <IndicatorIcon>{icon}</IndicatorIcon>
                    : <TipsIconStyle>i</TipsIconStyle>
                }
              </YPopover>
              <div>
                <IndicatorCardTitleStyle>{data.name}</IndicatorCardTitleStyle>
                <IndicatorCardMainStyle>
                  {
                    data.render
                      ? data.render(data.value)
                      : data.value
                  }
                </IndicatorCardMainStyle>
              </div>
            </IndicatorFlexStyle>;
          })
        }
      </IndicatorCardStyle>
    );
  };

  return (
    <IndicatorCardBoxStyle>
      {dataSource && dataSource.map((item: IIndicatorData, index: number) =>
        renderIndicatorCard(item, index),
      )}
    </IndicatorCardBoxStyle>
  );
};
