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

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>;
  handleCreateFolder: (name: string, parentId?: string | null) => Promise<FolderInfo>;
  handleRenameFolder: (folderId: string, name: string) => Promise<FolderInfo>;
  handleDeleteFolderCascade: (folderId: string) => Promise<{ deletedFolders: number; deletedFiles: number }>;
  handleMoveFolder: (folderId: string, parentId: string | null) => Promise<FolderInfo>;
  handleMoveFiles: (fileIds: string[], targetFolderId: string | null) => Promise<void>;
  fetchOwnFolderTree: () => Promise<FolderInfo[]>;
  fetchSharedFolderTree: () => Promise<FolderInfo[]>;
}

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();

  const {
    handleCreateFolder,
    handleRenameFolder,
    handleMoveFolder,
    handleDeleteFolderCascade,
    handleMoveFiles,
    fetchOwnFolderTree,
    fetchSharedFolderTree,
  } = useFolderOperations();

  return (
    <FileContext.Provider
      value={{
        handleFileUpload: hookHandleFileUpload,
        handleFileDelete: hookHandleFileDelete,
        handleFilePreview,
        handleFileDownload: async (fileId: string, fileName: string) => {
          await handleFileDownload(fileId, fileName);
        },
        uploadingFile,
        deletingFiles,
        previewingFiles,
        downloadingFiles,
        handleCreateFolder,
        handleRenameFolder,
        handleMoveFolder,
        handleDeleteFolderCascade,
        handleMoveFiles,
        fetchOwnFolderTree,
        fetchSharedFolderTree,
      }}
    >
      {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;
}
