import { useState, useCallback } from 'react';
import { GroundingSource } from '../types/ragGrounding';
import ImageDownloadService, { ImageDownloadOptions, ImageDownloadResult } from '../services/imageDownloadService';

/**
 * 图片下载状态
 */
export interface ImageDownloadState {
  /** 是否正在下载 */
  isDownloading: boolean;
  /** 下载进度 (0-100) */
  progress: number;
  /** 错误信息 */
  error: string | null;
  /** 最后下载的文件路径 */
  lastDownloadPath: string | null;
}

/**
 * 图片下载钩子返回值
 */
export interface UseImageDownloadReturn {
  /** 下载状态 */
  downloadState: ImageDownloadState;
  /** 下载单个图片 */
  downloadImage: (source: GroundingSource, options?: ImageDownloadOptions) => Promise<ImageDownloadResult>;
  /** 批量下载图片 */
  downloadImages: (sources: GroundingSource[], options?: ImageDownloadOptions) => Promise<ImageDownloadResult[]>;
  /** 检查图片是否可下载 */
  isDownloadable: (source: GroundingSource) => boolean;
  /** 重置状态 */
  resetState: () => void;
}

/**
 * 图片下载自定义钩子
 * 提供图片下载功能和状态管理
 */
export const useImageDownload = (): UseImageDownloadReturn => {
  const [downloadState, setDownloadState] = useState<ImageDownloadState>({
    isDownloading: false,
    progress: 0,
    error: null,
    lastDownloadPath: null
  });

  // 下载单个图片
  const downloadImage = useCallback(async (
    source: GroundingSource,
    options: ImageDownloadOptions = {}
  ): Promise<ImageDownloadResult> => {
    setDownloadState(prev => ({
      ...prev,
      isDownloading: true,
      progress: 0,
      error: null
    }));

    try {
      // 检查图片是否可下载
      if (!ImageDownloadService.isDownloadable(source)) {
        throw new Error('图片不可下载或URI无效');
      }

      // 模拟进度更新
      setDownloadState(prev => ({ ...prev, progress: 25 }));

      const result = await ImageDownloadService.downloadImage(source, options);

      setDownloadState(prev => ({ ...prev, progress: 100 }));

      if (result.success) {
        setDownloadState(prev => ({
          ...prev,
          isDownloading: false,
          lastDownloadPath: result.filePath || null,
          error: null
        }));
      } else {
        setDownloadState(prev => ({
          ...prev,
          isDownloading: false,
          error: result.error || '下载失败'
        }));
      }

      return result;

    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '下载失败';
      
      setDownloadState(prev => ({
        ...prev,
        isDownloading: false,
        error: errorMessage
      }));

      return {
        success: false,
        error: errorMessage
      };
    }
  }, []);

  // 批量下载图片
  const downloadImages = useCallback(async (
    sources: GroundingSource[],
    options: ImageDownloadOptions = {}
  ): Promise<ImageDownloadResult[]> => {
    setDownloadState(prev => ({
      ...prev,
      isDownloading: true,
      progress: 0,
      error: null
    }));

    try {
      const results: ImageDownloadResult[] = [];
      const total = sources.length;

      for (let i = 0; i < sources.length; i++) {
        const source = sources[i];
        
        // 更新进度
        const progress = Math.round((i / total) * 100);
        setDownloadState(prev => ({ ...prev, progress }));

        // 下载单个图片
        const result = await ImageDownloadService.downloadImage(source, {
          ...options,
          showSaveDialog: false // 批量下载时不显示对话框
        });

        results.push(result);

        // 如果有失败的，记录错误但继续下载其他图片
        if (!result.success && !downloadState.error) {
          setDownloadState(prev => ({
            ...prev,
            error: `部分图片下载失败: ${result.error}`
          }));
        }
      }

      setDownloadState(prev => ({
        ...prev,
        isDownloading: false,
        progress: 100
      }));

      return results;

    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '批量下载失败';
      
      setDownloadState(prev => ({
        ...prev,
        isDownloading: false,
        error: errorMessage
      }));

      return [];
    }
  }, [downloadState.error]);

  // 检查图片是否可下载
  const isDownloadable = useCallback((source: GroundingSource): boolean => {
    return ImageDownloadService.isDownloadable(source);
  }, []);

  // 重置状态
  const resetState = useCallback(() => {
    setDownloadState({
      isDownloading: false,
      progress: 0,
      error: null,
      lastDownloadPath: null
    });
  }, []);

  return {
    downloadState,
    downloadImage,
    downloadImages,
    isDownloadable,
    resetState
  };
};

export default useImageDownload;
