import React, { useContext } from 'react';
import { WidgetContext } from '../../WidgetProvider/WidgetProvider';
import { getWidgetBaseStyle, getWidgetTitle } from '../../WidgetManager/utils/utils';
import styled from 'styled-components/macro';
import { darken, getLuminance, lighten } from 'polished';
import { BoardActionContext } from '../../ActionProvider/BoardActionProvider';
import { DownloadFileType } from '../../../../../constants';
import { useSelector } from 'react-redux';
import { selectSharePermission } from '../../../../SharePage/slice/selectors';
import { message } from 'antd';
import useI18NPrefix from '../../../../../hooks/useI18NPrefix';
import { BoardContext } from '../../BoardProvider/BoardProvider';

export const ExportBtnWidgetCore: React.FC<{}> = () => {
  const widget = useContext(WidgetContext);
  const { onBoardToDownLoad } = useContext(BoardActionContext);
  const t = useI18NPrefix('viz')
  const sharePermission =  useSelector(selectSharePermission);
  const allowShareDownload = !!sharePermission?.allowDownload;
  const { allowDownload } = useContext(BoardContext);
  const onExport = e => {
    e.stopPropagation();
    if (allowDownload || allowShareDownload){
      onBoardToDownLoad?.(DownloadFileType.Excel);
    }else {
      message.error(t('action.share.unDataPermission'))
    }
  };

  const title = getWidgetTitle(widget.config.customConfig.props);
  title.title = widget.config.name;
  const { background } = getWidgetBaseStyle(widget.config.customConfig.props);
  return (
    <Wrapper color={background.color} onClick={onExport}>
      <span
        style={{
          color: title.font.color,
          fontSize: title.font.fontSize,
          fontWeight: title.font.fontWeight,
          fontFamily: title.font.fontFamily,
        }}
      >
        {title.title}
      </span>
    </Wrapper>
  );
};

const Wrapper = styled.div<{ color: string }>`
  display: flex;
  flex: 1;
  align-items: center;
  justify-content: center;

  cursor: pointer;
  &:hover {
    background: ${p =>
  getLuminance(p.color) > 0.5
    ? darken(0.05, p.color)
    : lighten(0.05, p.color)};
  }
`;
