import { useCallback, useRef, useState } from 'react';
import { downloadBlob } from '../utils/download';
import { message } from '../ui/app-message';

export interface DownloadOptions {
  /** 成功提示文案；默认「下载成功」 */
  successMsg?: string;
  /** 失败提示文案；默认使用接口返回的错误信息 */
  errorMsg?: string;
}

/**
 * 统一下载/导出状态：防重复点击 + 成功/失败反馈。
 *
 * 用法：
 *   const { downloading, run } = useDownload();
 *   <Button loading={downloading} onClick={() => run('/students/export', '名单.xlsx')}>
 */
export function useDownload() {
  const [downloading, setDownloading] = useState(false);
  const busyRef = useRef(false);

  const run = useCallback(
    async (endpoint: string, filename: string, options?: DownloadOptions) => {
      if (busyRef.current) return;
      busyRef.current = true;
      setDownloading(true);
      try {
        await downloadBlob(endpoint, filename);
        message.success(options?.successMsg ?? '下载成功');
      } catch (error: unknown) {
        message.error(
          options?.errorMsg ?? (error instanceof Error ? error.message : '下载失败，请重试'),
        );
      } finally {
        busyRef.current = false;
        setDownloading(false);
      }
    },
    [],
  );

  return { downloading, run };
}

export default useDownload;
