import { Button, ButtonProps, message } from 'antd';
import { DownloadOutlined } from '@ant-design/icons';
import api from '@/api/request';

interface Props extends Omit<ButtonProps, 'onClick'> {
  url: string;
  // 어떤 SearchParam VO 든 받을 수 있도록 unknown record
  params?: Record<string, unknown> | object;
  fileName: string;
}

/**
 * 대용량 엑셀 다운로드. axios responseType=blob, content-disposition 무시하고 fileName 강제.
 */
export default function ExcelExportButton({ url, params, fileName, ...rest }: Props) {
  const handleClick = async () => {
    try {
      const res = await api.get(url, { params, responseType: 'blob' });
      const blob = new Blob([res.data], {
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      });
      const link = document.createElement('a');
      link.href = URL.createObjectURL(blob);
      link.download = `${fileName}.xlsx`;
      link.click();
      URL.revokeObjectURL(link.href);
    } catch {
      message.error('엑셀 다운로드 실패');
    }
  };

  return (
    <Button icon={<DownloadOutlined />} onClick={handleClick} {...rest}>
      {rest.children ?? '엑셀'}
    </Button>
  );
}
