import {
  Download,
  FileAdditionOne,
  FileExcel,
  Refresh,
  Upload,
} from '@icon-park/react';
import {ChildrenFC, MENU_STORAGE} from '@utils';
import {Button, Space, Upload as AntUpload, UploadProps} from 'antd';
import css from './index.module.css';
import {useLocation} from 'react-router-dom';
import {useMemo} from 'react';
import {useSessionStorageState} from 'ahooks';
import {TreeRoleMenuData} from '@models';

type Props = {
  onAdd?: () => void;
  onRefresh?: () => void;
  onExport?: () => void;
  isExporting?: boolean;
  isRefreshing?: boolean;
  title?: string;
  onDownload?: () => void;
  uploadProps?: UploadProps;
  isUploading?: boolean;
};

const TableTools: ChildrenFC<Props> = function ({
  children,
  onAdd,
  onRefresh,
  onExport,
  isExporting,
  isRefreshing,
  title,
  onDownload,
  uploadProps,
  isUploading,
}) {
  const [pages] = useSessionStorageState<TreeRoleMenuData[]>(MENU_STORAGE);
  const {pathname} = useLocation();
  const menuTitle = useMemo(
    function () {
      return pages.find(val => val.url === pathname)?.name ?? '';
    },
    [pages, pathname],
  );

  return (
    <section className='table-tool'>
      <h1 className={css.title}>{title ?? menuTitle}</h1>
      <Space>
        {onAdd && (
          <Button
            type='primary'
            onClick={onAdd}
            data-testid='add_btn'
            icon={<FileAdditionOne theme='outline' className='anticon' />}
          >
            新增
          </Button>
        )}
        {onRefresh && (
          <Button
            className='ant-btn-color-green'
            data-testid='refresh_btn'
            onClick={onRefresh}
            loading={isRefreshing}
            icon={<Refresh theme='outline' className='anticon' />}
          >
            刷新
          </Button>
        )}
        {onDownload && (
          <Button
            onClick={onDownload}
            icon={<Download theme='outline' className='anticon' />}
          >
            模板下载
          </Button>
        )}
        {uploadProps && (
          <AntUpload {...uploadProps}>
            <Button
              loading={isUploading}
              icon={<Upload theme='outline' className='anticon' />}
            >
              模板上传
            </Button>
          </AntUpload>
        )}
        {onExport && (
          <Button
            data-testid='export_btn'
            onClick={onExport}
            loading={isExporting}
            icon={<FileExcel theme='outline' className='anticon' />}
          >
            导出
          </Button>
        )}
        {children}
      </Space>
    </section>
  );
};

export default TableTools;
