import React, { createContext, useContext } from 'react';
import { useFileOperations, type FilePreviewResult } from '../hooks/useFiles';

interface FileContextType {
  handleFileUpload: (file: File, workflowId?: string) => Promise<{ success: boolean; fileData?: any; error?: string }>;
  handleFileDelete: (fileId: string, onOptimisticDelete?: () => void) => Promise<boolean>;
  handleFilePreview: (fileId: string, fileName: string, mimeType?: string) => Promise<FilePreviewResult>;
  handleFileDownload: (fileId: string, fileName: string) => Promise<void>;
  uploadingFile: boolean;
  deletingFiles: Set<string>;
  previewingFiles: Set<string>;
  downloadingFiles: Set<string>;
}

export const FileContext = createContext<FileContextType | undefined>(undefined);

export function FileProvider({ children }: { children: React.ReactNode }) {
  const {
    handleFileUpload: hookHandleFileUpload,
    handleFileDelete: hookHandleFileDelete,
    handleFilePreview,
    handleFileDownload,
    uploadingFile,
    deletingFiles,
    previewingFiles,
    downloadingFiles,
  } = useFileOperations();

  return (
    <FileContext.Provider
      value={{
        handleFileUpload: hookHandleFileUpload,
        handleFileDelete: hookHandleFileDelete,
        handleFilePreview,
        handleFileDownload: async (fileId: string, fileName: string) => {
          await handleFileDownload(fileId, fileName);
        },
        uploadingFile,
        deletingFiles,
        previewingFiles,
        downloadingFiles,
      }}
    >
      {children}
    </FileContext.Provider>
  );
}

export function useFileContext() {
  const context = useContext(FileContext);
  if (context === undefined) {
    throw new Error('useFileContext must be used within a FileProvider');
  }
  return context;
}
