import React, { createContext, useContext, useCallback } from 'react';
import { useUserFiles, useFileOperations, UserFile } from '../hooks/useFiles';

interface FileContextType {
  files: UserFile[];
  loading: boolean;
  error: string | null;
  refetch: () => Promise<void>;
  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<{ success: boolean; previewUrl?: string | null; blob?: Blob; isJsonContent?: boolean; decodedContent?: string; error?: string }>;
  handleFileDownload: (fileId: string, fileName: string) => Promise<void>;
  uploadingFile: boolean;
  deletingFiles: Set<string>;
  previewingFiles: Set<string>;
  downloadingFiles: Set<string>;
}

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

export function FileProvider({ children }: { children: React.ReactNode }) {
  const { data: files, loading, error, refetch: refetchFiles, removeFileOptimistically } = useUserFiles();
  const {
    handleFileUpload: hookHandleFileUpload,
    handleFileDelete: hookHandleFileDelete,
    handleFilePreview,
    handleFileDownload,
    uploadingFile,
    deletingFiles,
    previewingFiles,
    downloadingFiles
  } = useFileOperations();

  // Centralized file upload that updates the shared state
  const handleFileUpload = useCallback(async (file: File, workflowId?: string) => {
    const result = await hookHandleFileUpload(file, workflowId);
    
    if (result.success && result.fileData) {
      // The API response structure: { message, file: FileInfo, ... }
      // The file data is nested in the 'file' property
      const responseData = result.fileData;
      const fileData = responseData.file || responseData; // Support both nested and direct structure
      
      if (!fileData || !fileData.id) {
        console.error('File upload response missing file data:', responseData);
        return result;
      }
      
      // File will be added via refetch
      // Refetch to ensure we have the latest data (this will update all consumers)
      await refetchFiles();
    }
    
    return result;
  }, [hookHandleFileUpload, refetchFiles]);

  // Centralized file delete that updates the shared state
  const handleFileDelete = useCallback(async (fileId: string, onOptimisticDelete?: () => void) => {
    const success = await hookHandleFileDelete(fileId, () => {
      removeFileOptimistically(fileId);
      onOptimisticDelete?.();
    });
    
    if (success) {
      // Refetch to ensure we have the latest data
      await refetchFiles();
    }
    
    return success;
  }, [hookHandleFileDelete, removeFileOptimistically, refetchFiles]);

  // Expose refetch function
  const refetch = useCallback(async () => {
    await refetchFiles();
  }, [refetchFiles]);

  return (
    <FileContext.Provider
      value={{
        files,
        loading,
        error,
        refetch,
        handleFileUpload,
        handleFileDelete,
        handleFilePreview,
        handleFileDownload,
        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;
}

