import { useState, useCallback } from 'react';
import {
  FileInfo,
  UploadProgress,
  uploadFile,
  validateFile,
  getFileType,
} from '../services/fileService';

interface UseFileUploadOptions {
  userId: string | null;
  conversationId?: string | null;
  onUploadComplete?: (file: FileInfo) => void;
  onUploadError?: (error: string, fileName: string) => void;
}

interface PendingFile {
  id: string;
  file: File;
  preview?: string;
  type: 'image' | 'document' | 'other';
}

export function useFileUpload({
  userId,
  conversationId,
  onUploadComplete,
  onUploadError,
}: UseFileUploadOptions) {
  const [pendingFiles, setPendingFiles] = useState<PendingFile[]>([]);
  const [uploadProgress, setUploadProgress] = useState<Record<string, UploadProgress>>({});
  const [isUploading, setIsUploading] = useState(false);

  // 添加待上传文件
  const addFiles = useCallback((files: FileList | File[]) => {
    const newFiles: PendingFile[] = [];

    Array.from(files).forEach((file) => {
      const validation = validateFile(file);
      if (!validation.valid) {
        onUploadError?.(validation.error!, file.name);
        return;
      }

      const id = `pending_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
      const type = getFileType(file.type);

      const pendingFile: PendingFile = {
        id,
        file,
        type,
      };

      // 为图片生成预览
      if (type === 'image') {
        pendingFile.preview = URL.createObjectURL(file);
      }

      newFiles.push(pendingFile);
    });

    setPendingFiles((prev) => [...prev, ...newFiles]);
  }, [onUploadError]);

  // 移除待上传文件
  const removeFile = useCallback((id: string) => {
    setPendingFiles((prev) => {
      const file = prev.find((f) => f.id === id);
      if (file?.preview) {
        URL.revokeObjectURL(file.preview);
      }
      return prev.filter((f) => f.id !== id);
    });
    setUploadProgress((prev) => {
      const { [id]: _, ...rest } = prev;
      return rest;
    });
  }, []);

  // 清空所有待上传文件
  const clearFiles = useCallback(() => {
    pendingFiles.forEach((f) => {
      if (f.preview) {
        URL.revokeObjectURL(f.preview);
      }
    });
    setPendingFiles([]);
    setUploadProgress({});
  }, [pendingFiles]);

  // 上传单个文件
  const uploadSingleFile = useCallback(
    async (pendingFile: PendingFile): Promise<FileInfo | null> => {
      if (!userId) return null;

      setUploadProgress((prev) => ({
        ...prev,
        [pendingFile.id]: {
          fileId: pendingFile.id,
          fileName: pendingFile.file.name,
          progress: 0,
          status: 'uploading',
        },
      }));

      try {
        const fileInfo = await uploadFile(
          pendingFile.file,
          userId,
          conversationId || undefined,
          (progress) => {
            setUploadProgress((prev) => ({
              ...prev,
              [pendingFile.id]: {
                ...prev[pendingFile.id],
                progress,
              },
            }));
          },
        );

        setUploadProgress((prev) => ({
          ...prev,
          [pendingFile.id]: {
            ...prev[pendingFile.id],
            progress: 100,
            status: 'success',
          },
        }));

        onUploadComplete?.(fileInfo);
        return fileInfo;
      } catch (error) {
        const errorMessage = error instanceof Error ? error.message : '上传失败';
        setUploadProgress((prev) => ({
          ...prev,
          [pendingFile.id]: {
            ...prev[pendingFile.id],
            status: 'error',
            error: errorMessage,
          },
        }));
        onUploadError?.(errorMessage, pendingFile.file.name);
        return null;
      }
    },
    [userId, conversationId, onUploadComplete, onUploadError],
  );

  // 上传所有待上传文件
  const uploadAllFiles = useCallback(async (): Promise<FileInfo[]> => {
    if (!userId || pendingFiles.length === 0) return [];

    setIsUploading(true);
    const uploadedFiles: FileInfo[] = [];

    for (const pendingFile of pendingFiles) {
      const fileInfo = await uploadSingleFile(pendingFile);
      if (fileInfo) {
        uploadedFiles.push(fileInfo);
      }
    }

    // 清理已成功上传的文件
    const successIds = Object.entries(uploadProgress)
      .filter(([_, p]) => p.status === 'success')
      .map(([id]) => id);

    setPendingFiles((prev) => prev.filter((f) => !successIds.includes(f.id)));

    setIsUploading(false);
    return uploadedFiles;
  }, [userId, pendingFiles, uploadProgress, uploadSingleFile]);

  return {
    pendingFiles,
    uploadProgress,
    isUploading,
    addFiles,
    removeFile,
    clearFiles,
    uploadAllFiles,
    hasPendingFiles: pendingFiles.length > 0,
  };
}
